package org.ezplatform.office.meeting.info.web.rest;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.ezplatform.cloud.api.component.attachment.AttachmentUtilsService;
import org.ezplatform.cloud.api.component.popuser.PopUserScopeUtilService;
import org.ezplatform.cloud.api.system.user.UserApiService;
import org.ezplatform.cloud.common.client.RestClient;
import org.ezplatform.cloud.common.log.LogService;
import org.ezplatform.component.popuser.service.CmpPopUserOrgName;
import org.ezplatform.core.common.WebUser;
import org.ezplatform.core.pagination.PropertyFilter;
import org.ezplatform.core.service.BaseService;
import org.ezplatform.core.web.controller.BaseController;
import org.ezplatform.core.web.util.WebUtils;
import org.ezplatform.core.web.view.OperationResult;
import org.ezplatform.mobile.util.common.service.CommonService;
import org.ezplatform.mobile.util.paramdata.service.MobileParamdataService;
import org.ezplatform.office.meeting.common.util.CycleMeetingThread;
import org.ezplatform.office.meeting.common.util.MeetingSendMsgUtils;
import org.ezplatform.office.meeting.common.util.MeetingUtils;
import org.ezplatform.office.meeting.info.entity.ApplyRecord;
import org.ezplatform.office.meeting.info.entity.QSMeetingInfo;
import org.ezplatform.office.meeting.info.entity.SignedAddress;
import org.ezplatform.office.meeting.info.entity.SignedInfo;
import org.ezplatform.office.meeting.info.service.ApplyRecordService;
import org.ezplatform.office.meeting.info.service.MeetingScopeService;
import org.ezplatform.office.meeting.info.service.QSMeetingService;
import org.ezplatform.office.meeting.info.service.SignedAddressService;
import org.ezplatform.office.meeting.info.service.SignedInfoService;
import org.ezplatform.office.meeting.memo.service.MemoInfoService;
import org.ezplatform.office.meeting.notice.service.NoticeInfoService;
import org.ezplatform.office.meeting.notice.service.NoticeTurnoverService;
import org.ezplatform.office.meeting.setting.boardroom.entity.BoardroomSet;
import org.ezplatform.office.meeting.setting.boardroom.service.BoardroomSetService;
import org.ezplatform.office.meeting.setting.serve.entity.ServeSet;
import org.ezplatform.office.meeting.setting.serve.service.ServeSetService;
import org.ezplatform.office.meeting.setting.type.entity.MeetingType;
import org.ezplatform.office.meeting.setting.type.service.MeetingTypeService;
import org.ezplatform.office.meeting.task.service.MeetingTaskInfoService;
import org.ezplatform.util.DateUtils;
import org.ezplatform.util.GlobalConstant;
import org.ezplatform.util.JsonUtils;
import org.ezplatform.util.StringUtils;
import org.ezplatform.util.UuidUtils;
import org.ezplatform.util.ValidateUtils;
import org.ezplatform.util.context.SpringContextHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.swetake.util.Qrcode;

/**
 * @ClassName: ApplyRecordController
 * @Description: 会议申请记录控制类
 * 注解
 */
@RestController
@RequestMapping(value = "/api/w/applyRecordController")
public class ApplyRecordWebApiController extends BaseController<ApplyRecord, String> {
	private final static Logger LOGGER = LoggerFactory.getLogger(ApplyRecordWebApiController.class);
		
    private String msg = "";
    @Lazy
	@Autowired
	private ApplyRecordService service;
	
	@Autowired
    private PopUserScopeUtilService popUserScopeUtilService;

	@Autowired
    private MeetingUtils meetingUtils;
	@Lazy
	@Autowired
    private ServeSetService serveSetService;
	@Lazy
	@Autowired
    private BoardroomSetService boardroomSetService;
	@Lazy
	@Autowired
	private UserApiService userApiService;
	@Lazy
	@Autowired
	private MeetingTaskInfoService meetingTaskInfoService;
	@Lazy
	@Autowired
	private SignedAddressService signedAddressService;
	@Lazy
	@Autowired
	private SignedInfoService signedInfoService;
	@Lazy
	@Autowired
	private NoticeInfoService noticeInfoService;
	@Lazy
	@Autowired
	private MemoInfoService memoInfoService;
	@Lazy
	@Autowired
	private NoticeTurnoverService noticeTurnoverService;

	@Autowired
	private MeetingSendMsgUtils meetingSendMsgUtils;
	@Lazy
	@Autowired
    private MeetingTypeService meetingTypeService;
	@Lazy
	@Autowired
    private AttachmentUtilsService attachmentUtilsService;
	
//	@Autowired
//	private UrlconvertService urlconvertService;
	@Lazy
	@Autowired
	private MobileParamdataService mobileParamdataService;
	
	@Autowired
	private LogService logService;
	@Lazy
	@Autowired
	private QSMeetingService qsMeetingService;
	@Lazy
	@Autowired
    private MeetingScopeService meetingScopeService;
	@Lazy
	@Autowired
	private CommonService commonService;
	
	@Autowired
	private CmpPopUserOrgName cmpPopUserOrgName;
	
	@Autowired
	private DataSource datasource;
	
    @Autowired
    private RestClient restClient;
	
	@Override
	protected BaseService<ApplyRecord, String> getEntityService() {
		return service;
	}

	/**
	 * 
	 * @Title: prepareModel
	 * @Description: 初始化数据
	 * @param request
	 * @param model
	 * @param id
	 * @return void
	 * @throws
	 */
	@ModelAttribute
	public void prepareModel(HttpServletRequest request, Model model,
			@RequestParam(value = "id", required = false) String id) {
		super.initPrepareModel(request, model, id);
	}

	@RequestMapping(value = "/entityIsExist", method = RequestMethod.POST)
	public OperationResult entityIsExist(String id) {
		ApplyRecord entity = this.service.findOne(id);
		if(entity == null) return OperationResult.buildSuccessResult("notExist");
		else return OperationResult.buildSuccessResult("exist");
	}
	
	@RequestMapping(value = "/cycleEntityIsExist", method = RequestMethod.POST)
	public OperationResult cycleEntityIsExist(String id) {
		WebUser user = WebUtils.getCurrentUser();
        String corpId = user.getCorpId();
		List<ApplyRecord> list = this.service.findListByProperty("cycleId", id, corpId);
		if(CollectionUtils.isEmpty(list)) return OperationResult.buildSuccessResult("notExist");
		else return OperationResult.buildSuccessResult("exist");
	}
	
	/**
     * 保存/修改,未同步通知
     *
     * @param entity
     * @param model
     * @return
     */
    @RequestMapping(value = "/editSaveWithoutNotice", method = RequestMethod.POST)
    public OperationResult editSaveWithoutNotice(@ModelAttribute("entity") ApplyRecord entity, Model model,HttpServletRequest request) {
    	WebUser user = WebUtils.getCurrentUser();
        String corpId = user.getCorpId();
        String id = ValidateUtils.filter(entity.getId());
        String boardroomId = entity.getBoardroomId();
    	String startTime = entity.getStartTime();
        String endTime = entity.getEndTime();
        List<Map<String, String>> cyclelist = null;
        if(StringUtils.isBlank(request.getParameter("meetingPeopleNum"))) {
        	entity.setMeetingPeopleNum(null);
        }
        if(StringUtils.isNotEmpty(boardroomId)) {
        	//校验时间
        	msg = this.boardroomSetService.checkTime(boardroomId,startTime, endTime,corpId);
	        if (StringUtils.isNotEmpty(msg)) {
	            return OperationResult.buildFailureResult(msg);
	        }
	        //验证会议室在会议开始结束时间范围内是否已有会议
	        msg = this.service.checkApplyRecordDate(id,startTime, endTime,boardroomId, corpId);
	        if (StringUtils.isNotEmpty(msg)) {
	            return OperationResult.buildFailureResult(msg);
	        }
	        //检测该会议室再周期内是否被占用
	        if(entity.getIsCycle() == 1) {
	        	cyclelist = this.service.getCycleDateList(entity);
	        	msg = this.service.checkCycleApplyRecordDate(entity, cyclelist, corpId);
	        	if (StringUtils.isNotEmpty(msg)) return OperationResult.buildFailureResult(msg);
	        }
        }else {
        	if(entity.getIsCycle() == 1) {
	        	cyclelist = this.service.getCycleDateList(entity);
	        }
        }
        entity.setStatus(1);
        OperationResult result = super.editSave(entity);
        if(entity.getIsCycle() == 1)  this.service.saveCycleMeeting(entity, cyclelist, true);
        return result;
    }
    
    /**
     * 选择已预定周期会议室发起会议
     * @param entity
     * @param request
     * @return
     */
    @RequestMapping(value = "/saveApplyBoardroomCycleMeeting", method = RequestMethod.POST)
    public OperationResult saveApplyBoardroomCycleMeeting(@ModelAttribute("entity") ApplyRecord entity, HttpServletRequest request) {
    	Map failureMap = new HashMap();
    	try {
			WebUser user = WebUtils.getCurrentUser();
			String corpId = user.getCorpId();
			String addrListJson = StringUtils.null2String(request.getParameter("addrList"));
			entity.setStatus(1);
			// 主持人
			String emceeUserJsonStr = StringUtils.null2String(request.getParameter("jsonStrEmceeUser"));
			String emceeUser = StringUtils.null2String(entity.getEmceeUser());
			if ("".equals(emceeUser)) {
			    emceeUser = UuidUtils.UUID();
			    entity.setEmceeUser(emceeUser);
			}
			this.popUserScopeUtilService.saveScopeData("oa_meeting_apply_record_scope", emceeUser, emceeUserJsonStr,
			        "oa_meeting_apply_record", "emcee_user");
			// 纪要员
			String memoUserJsonStr = StringUtils.null2String(request.getParameter("jsonStrMemoUser"));
			String memoUser = StringUtils.null2String(entity.getMemoUser());
			if ("".equals(memoUser)) {
			    memoUser = UuidUtils.UUID();
			    entity.setMemoUser(memoUser);
			}
			this.popUserScopeUtilService.saveScopeData("oa_meeting_apply_record_scope", memoUser, memoUserJsonStr,
			        "oa_meeting_apply_record", "memo_user");
			// 参会人
			String attendUserJsonStr = StringUtils.null2String(request.getParameter("jsonStrAttendUser"));
			String attendUser = StringUtils.null2String(entity.getAttendUser());
			if ("".equals(attendUser)) {
			    attendUser = UuidUtils.UUID();
			    entity.setAttendUser(attendUser);
			}
			this.popUserScopeUtilService.saveScopeData("oa_meeting_apply_record_scope", attendUser, attendUserJsonStr,
			        "oa_meeting_apply_record", "attend_user");
			
			String cycleId = entity.getCycleId();
			//查询还未使用的周期会议室
			List<ApplyRecord> arCycleList = this.service.getApplyRecordListByCycleId(cycleId, corpId);
			if(CollectionUtils.isNotEmpty(arCycleList)) {
				for(ApplyRecord a : arCycleList) {
					this.service.applyRecordCopy(a, entity);
				}
			}
			List<ApplyRecord> resultList = this.service.save(arCycleList);
			if(CollectionUtils.isNotEmpty(resultList)) {
				ApplyRecord ar = arCycleList.get(0);
				List<String> newUserIdList = this.service.getApplyRecordUserList(ar, TOKEN);
				//会议签到地址
				String signType = ar.getSignedType();
				if(ar.getIsSigned()==1 && ("1".equals(signType)||"2".equals(signType))){
					this.signedAddressService.saveSignedAddress(ar.getId(), addrListJson);
				}
				
			    //保存周期会议
			    if(ar.getIsCycle() == 1) {
			    	CycleMeetingThread cycThread = new CycleMeetingThread(resultList, newUserIdList, "", corpId, ar.getIsSigned());
			    	cycThread.start();
			    }
			    String applyRecordId = ar.getId();
			    Map<String, Object> ds = new HashMap<>();
			    ds.put("applyRecordId", applyRecordId);
				ds.put("meetingTitle", ar.getName());
				ds.put("startTime", ar.getStartTime());
				BoardroomSet room = this.boardroomSetService.findOne(ar.getBoardroomId());
				ds.put("boardroom", room == null ? (StringUtils.isNotEmpty(ar.getAddress()) ? ar.getAddress():"无") : room.getAddress());
			    String noticeUserId = ar.getCreatedBy();
			    String userName = "";
			    if(StringUtils.isNotEmpty(noticeUserId)){
			        Map<String, Object> userInfo = this.userApiService.getUser(noticeUserId, corpId,  "", TOKEN);
			        if(userInfo != null){
			            userName = StringUtils.null2String(userInfo.get("userName"));
			        }
			    }
				ds.put("userId", noticeUserId);
				ds.put("userName", userName);
				ds.put("userOrg", ar.getCreatedOrg());
				ds.put("type", "2");
				boolean mobilePush = false;
			    boolean emailPush = false;
			    boolean smsPublish = false;
				String mesgPush = ar.getMessagePush();
				if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("mobile")) mobilePush = true;
				if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("email")) emailPush = true;
				if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("sms")) smsPublish = true;
				if(CollectionUtils.isNotEmpty(newUserIdList)) sendMessageToUser(emailPush, mobilePush, smsPublish, newUserIdList, ds, corpId, request);
			}
		} catch (Exception e) {
			e.printStackTrace();
			failureMap.put("i18NCode", "oa.meeting.savefalse");
			OperationResult.buildFailureResult("保存失败",failureMap);
		}
    	failureMap.put("i18NCode", "oa.meeting.savesuccess");
	    return OperationResult.buildSuccessResult("保存成功",failureMap);    	
    }
	
	/**
     * 保存/修改,同步通知
     *
     * @param entity
     * @param model
     * @return
     */
    @RequestMapping(value = "/editSave", method = RequestMethod.POST)
    public OperationResult editSave(@ModelAttribute("entity") ApplyRecord entity, String deleteId, HttpServletRequest request) {
    	LOGGER.debug("-----editSave----");
    	Map failureMap = new HashMap();
		try {
			WebUser user = WebUtils.getCurrentUser();
			String corpId = user.getCorpId();
			String curUserId = user.getUserId();
			String addrListJson = StringUtils.null2String(request.getParameter("addrList"));
			String id = StringUtils.null2String(entity.getId());
			boolean isEdit = false;
			boolean meetingInfoIsChange = false;
			List<String> oldUserIdList = null;
			
			int oldMeetingWay = 0;
			String oldcreateBy = "";
			String manageMenu=StringUtils.null2String(request.getParameter("manageMenu"));
			if(StringUtils.isBlank(request.getParameter("meetingPeopleNum"))) {
	        	entity.setMeetingPeopleNum(null);
	        }
			if(StringUtils.isNotBlank(id)) {
				ApplyRecord oldEntity = this.service.findOne(id);
				if(StringUtils.isNotEmpty(oldEntity.getBoardroomId())) {
					entity.setMeetingServe(oldEntity.getMeetingServe());
					//判断是不是审批会议
					BoardroomSet approve = this.boardroomSetService.findOne(oldEntity.getBoardroomId());
					if(Integer.valueOf("1").equals(oldEntity.getStatus())&&"1".equals(approve.getIsApprove())&& "meetingSearch".equals(manageMenu)) {
						//审批会议，会议查询，需求只让更新会议名称和参会人
						oldEntity.setName(entity.getName());
						oldEntity.setAttendUser(entity.getAttendUser());
						//项目需要：添加会议开始时间和结束时间
						oldEntity.setStartTime(entity.getStartTime());
						oldEntity.setEndTime(entity.getEndTime());
						entity=oldEntity;
					}
				}
				oldMeetingWay = oldEntity.getMeetingWay();
				oldcreateBy = oldEntity.getCreatedBy();
				if(entity.getIsSync() == 1 && StringUtils.isNotBlank(oldEntity.getName())) {
					isEdit = true;
					//编辑时，会议室有变更的话
					this.service.changeBoardroom(entity, oldEntity, deleteId);
					meetingInfoIsChange = isEntityChanged(entity, oldEntity, addrListJson, corpId);
					oldUserIdList = this.service.getApplyRecordUserList(entity, TOKEN);
				}
				
			}else {
				String meetingServe = StringUtils.null2String(request.getParameter("meetingServe"));
				if(!"".equals(meetingServe)) {
					entity.setMeetingServe(meetingServe);
				}
			}
			String startTime = entity.getStartTime();
			String endTime = entity.getEndTime();
			String boardroomId = entity.getBoardroomId();
			List<Map<String, String>> cyclelist = null;
			BoardroomSet room = null;
			String meetingPeopleNum = StringUtils.null2String(request.getParameter("meetingPeopleNum"));
			if(!"".equals(meetingPeopleNum)) {
				entity.setMeetingPeopleNum(Integer.valueOf(meetingPeopleNum));
			}
			//保存前 验证
			//验证会议开始结束时间是否在会议室的范围内
			if(StringUtils.isNotEmpty(boardroomId)) {
				
				room = this.boardroomSetService.findOne(boardroomId);
		    	msg = this.boardroomSetService.checkTime(boardroomId,startTime, endTime,corpId);
		        if (StringUtils.isNotEmpty(msg)) {
		            return OperationResult.buildFailureResult(msg);
		        }
			    //验证会议室在会议开始结束时间范围内是否已有会议
			    msg = this.service.checkApplyRecordDate(id,startTime, endTime,boardroomId, corpId);
			    if (StringUtils.isNotEmpty(msg)) {
			        return OperationResult.buildFailureResult(msg);
			    }
			    //检测该会议室再周期内是否被占用
			    if(entity.getIsCycle() == 1) {
			    	cyclelist = this.service.getCycleDateList(entity);
			    	msg = this.service.checkCycleApplyRecordDate(entity, cyclelist, corpId);
			    	if (StringUtils.isNotEmpty(msg)) return OperationResult.buildFailureResult(msg);
			    }
			}else {
				if(entity.getIsCycle() == 1) {
			    	cyclelist = this.service.getCycleDateList(entity);
			    }
			}
			entity.setStatus(1);
			
			// 主持人
			String emceeUserJsonStr = StringUtils.null2String(request.getParameter("jsonStrEmceeUser"));
			String emceeUserName ="";
			if(emceeUserJsonStr!="") {
				List<Map<String,Object>> emceeUserMap=JsonUtils.readListValue(emceeUserJsonStr);
				if(emceeUserMap.size()>0) {
					emceeUserName=StringUtils.null2String(emceeUserMap.get(0).get("scopeName"));
				}
			}
			String emceeUser = StringUtils.null2String(entity.getEmceeUser());
			if ("".equals(emceeUser)) {
			    emceeUser = UuidUtils.UUID();
			    entity.setEmceeUser(emceeUser);
			}
			// 纪要员
			String memoUserJsonStr = StringUtils.null2String(request.getParameter("jsonStrMemoUser"));
			String memoUser = StringUtils.null2String(entity.getMemoUser());
			if ("".equals(memoUser)) {
			    memoUser = UuidUtils.UUID();
			    entity.setMemoUser(memoUser);
			}
			// 参会人
			String attendUserJsonStr = StringUtils.null2String(request.getParameter("jsonStrAttendUser"));
			String attendUser = StringUtils.null2String(entity.getAttendUser());
			if ("".equals(attendUser)) {
			    attendUser = UuidUtils.UUID();
			    entity.setAttendUser(attendUser);
			}
			// 会议列席人
			String attendantsJsonStr = StringUtils.null2String(request.getParameter("jsonStrAttendants"));
			String attendants = StringUtils.null2String(entity.getMeetingAttendants());
			if ("".equals(attendants)) {
				attendants = UuidUtils.UUID();
			    entity.setMeetingAttendants(attendants);
			}			
			String emceeUserThread=emceeUser;
			String memoUserThread=memoUser;
			String attendUserThread=attendUser;
			String attendantsThread=attendants;
//			MeetingUtils.execute(()->{
				popUserScopeUtilService.saveScopeData("oa_meeting_apply_record_scope", emceeUserThread, emceeUserJsonStr,"oa_meeting_apply_record", "emcee_user");
				popUserScopeUtilService.saveScopeData("oa_meeting_apply_record_scope", memoUserThread, memoUserJsonStr, "oa_meeting_apply_record", "memo_user");
				popUserScopeUtilService.saveScopeData("oa_meeting_apply_record_scope", attendUserThread, attendUserJsonStr, "oa_meeting_apply_record", "attend_user");
				popUserScopeUtilService.saveScopeData("oa_meeting_apply_record_scope", attendantsThread, attendantsJsonStr, "oa_meeting_apply_record", "meeting_attendants");
//			});
			//----全时会议处理--start
			int meetingWay = entity.getMeetingWay();
			LOGGER.debug("tMeetingWay："+meetingWay);
			//修改后是网络会议
			boolean newIsWeb = false;
			if(meetingWay==1 || meetingWay==2) {
				newIsWeb = true;
			}
			LOGGER.debug("newIsWeb："+newIsWeb);
			
			OperationResult result = null;
			//修改会议通知
			if(StringUtils.isNotBlank(id)) {
				
				LOGGER.debug("oldMeetingWay："+oldMeetingWay);
				//修改前是网络会议
				boolean oldIsWeb = false;
				if(oldMeetingWay==1 || oldMeetingWay==2) {
					oldIsWeb = true;
				}
				LOGGER.debug("oldIsWeb："+oldIsWeb);
				if(newIsWeb) {
					if(oldIsWeb) {
						//修改全时
						String qsDesp = qsMeetingService.updateQSMeeting(id,entity,oldcreateBy,user.getJwtToken());
						if(!"0".equals(qsDesp)) {
							return OperationResult.buildFailureResult(qsDesp);
						}
						result = super.editSave(entity);
					}else {
						
						//新增
						Map map = qsMeetingService.newQSMeeting(entity.getName(),
								                                          entity.getStartTime(),
								                                          entity.getEndTime(),
								                                          curUserId,
								                                          user.getJwtToken());
						String success = map.get("success")+"";
						if("0".equals(success)) {
							//成功 保存主表数据
							result = super.editSave(entity);
							QSMeetingInfo info = (QSMeetingInfo) map.get("info");
							//保存全时会议信息
							//String emceeUserId = this.service.getEmceeUser(entity);
							info.setMeetingApplyId(entity.getId());
							info.setEmceeUser(entity.getCreatedBy());
							qsMeetingService.saveQSMeetingInfo(info);
						}else {
							String msg = (String) map.get("msg");
							return OperationResult.buildFailureResult(msg);
						}

					}
				}else {
					if(oldIsWeb) {
						//取消
						qsMeetingService.delQSMeeting(id,oldcreateBy,user.getJwtToken());
					}
					//非网络会议
					result = super.editSave(entity);
				}
				
			}else {
				//新增 网络会议  开全时会议
				if(newIsWeb) {
					Map map = qsMeetingService.newQSMeeting(entity.getName(),
								                            entity.getStartTime(),
								                            entity.getEndTime(),
								                            curUserId,
								                            user.getJwtToken());
					String success = map.get("success")+"";
					if("0".equals(success)) {
						//成功 保存主表数据
						result = super.editSave(entity);
						QSMeetingInfo info = (QSMeetingInfo) map.get("info");
						//保存全时会议信息
						//String emceeUserId = this.service.getEmceeUser(entity);
						info.setMeetingApplyId(entity.getId());
						info.setEmceeUser(entity.getCreatedBy());
						qsMeetingService.saveQSMeetingInfo(info);
					}else {
						String msg = (String) map.get("msg");
						LOGGER.info(msg);
						return OperationResult.buildFailureResult("预约失败，请检查网络会议配置");
					}

				}else {
					//非网络会议
					result = super.editSave(entity);
				}
				
				
			}
			//----全时会议处理--end
			long time=System.currentTimeMillis();
			//记录新建日志
	        if(StringUtils.isEmpty(id) && logService.checkOptLog(corpId, "meeting:start:02", TOKEN)) {//判断是否记录日志
	        	LOGGER.debug("------zhaozy1:"+(System.currentTimeMillis()-time));
	        	time=System.currentTimeMillis();
				logService.saveModuleLogAsync("meeting:start:02", entity.getName(), "",request);  
				LOGGER.debug("------zhaozy2:"+(System.currentTimeMillis()-time));
	        	time=System.currentTimeMillis();
			}
			if(result.getCode() == "0"){
				List<String> newUserIdList = this.service.getApplyRecordUserList(entity, TOKEN);
				LOGGER.debug("-1----newUserIdList："+newUserIdList.size());
				List<String> addList = null;
				List<String> noticeUpdateList = null;
				//会议签到地址
				String signType = entity.getSignedType();
				if(entity.getIsSigned()==1 && ("1".equals(signType)||"2".equals(signType))){
					this.signedAddressService.saveSignedAddress(entity.getId(), addrListJson);
				}
//				if(!"0".equals(isApprove)){
//					this.service.saveApplyRecord(entity);
//				}else {
					//this.service.editSaveByStatus(entity,"1","",TOKEN);
					if(isEdit) {
						addList = new ArrayList<String>();
			        	noticeUpdateList = new ArrayList<String>();
			        	//获取新增加的参会人id
						for(String newId : newUserIdList) {
							if(!oldUserIdList.contains(newId)) {
								addList.add(newId);
							}
						}
						//获取已参加的人id
						for(String oldUserId : oldUserIdList) {
							if(newUserIdList.contains(oldUserId)) {
								noticeUpdateList.add(oldUserId);
							}
						}
						this.noticeInfoService.deleteNoticeInfoByApplyrecordId(id, corpId);
						this.noticeTurnoverService.deleteNoticeTurnover(id, corpId);
						this.signedInfoService.deleteSignedInfoByApplyrecordId(id, corpId);
					}
					//新建会议通知数据
					this.noticeInfoService.addNoticeInfo(newUserIdList, entity.getId(), corpId);
					//新建会议签到数据
			        if(entity.getIsSigned() == 1) this.signedInfoService.addSignedInfo(newUserIdList, entity.getId(), corpId);
			        //保存周期会议
			        if(entity.getIsCycle() == 1) {
			        	List<ApplyRecord> arCycleList = this.service.saveCycleMeeting(entity, cyclelist);
			        	//                	this.noticeInfoService.addCycleNoticeInfo(arCycleList, newUserIdList, entity.getId(), corpId);
//                	if(entity.getIsSigned() == 1) this.signedInfoService.addCycleSignedInfo(arCycleList, newUserIdList, entity.getId(), corpId);
			        	CycleMeetingThread cycThread = new CycleMeetingThread(arCycleList, newUserIdList, entity.getId(), corpId, entity.getIsSigned());
			        	cycThread.start();
			        }else if(StringUtils.isNotBlank(entity.getCycleId())){
				    	//如果是从周期会议室中挑选的一个会议室发起的普通会议，那么该周期会议室全都变成普通会议会议室
				    	this.service.updateIsCycle(entity.getCycleId());
				    }
//				}
			    String applyRecordId = entity.getId();
			    Map<String, Object> ds = new HashMap<>();
			    ds.put("applyRecordId", applyRecordId);
				ds.put("meetingTitle", entity.getName());
				ds.put("startTime", entity.getStartTime());
				ds.put("endTime", entity.getEndTime());
				ds.put("emceeUserName", emceeUserName);
				LOGGER.debug("---entity.getAddress():"+entity.getAddress());
				ds.put("boardroom", room == null ? (StringUtils.isNotEmpty(entity.getAddress()) ? entity.getAddress():"无") : room.getAddress());
				LOGGER.debug("---ds.boardroom:"+ds.get("boardroom"));
				String noticeUserId = entity.getCreatedBy();
			    String userName = "";
			    if(StringUtils.isNotEmpty(noticeUserId)){
//			        Map<String, Object> userInfo = this.userApiService.getUser(noticeUserId, corpId,  "", TOKEN);
			        userName = cmpPopUserOrgName.getUserNameById(noticeUserId);
//			        if(userInfo != null){
//			            userName = StringUtils.null2String(userInfo.get("userName"));
//			        }
			    }
				ds.put("userId", noticeUserId);
				ds.put("userName", userName);
				ds.put("userOrg", entity.getCreatedOrg());
				ds.put("type", "2");
				boolean mobilePush = false;
			    boolean emailPush = false;
			    boolean smsPublish = false;
				String mesgPush = entity.getMessagePush();
				LOGGER.debug("---mesgPush:"+mesgPush);
				if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("mobile")) mobilePush = true;
				if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("email")) emailPush = true;
				if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("sms")) smsPublish = true;
				if(isEdit) {
					//新增的参会人员发送邀请通知
					if(CollectionUtils.isNotEmpty(addList)) sendMessageToUser(emailPush, mobilePush, smsPublish, addList, ds, corpId, request);
					//已参会人员发送变更通知
					if(CollectionUtils.isNotEmpty(noticeUpdateList) && meetingInfoIsChange) {
						ds.put("type", "9");
						sendMessageToUser(emailPush, mobilePush, smsPublish, noticeUpdateList, ds, corpId, request);
					}
				}else {
					if(CollectionUtils.isNotEmpty(newUserIdList)) sendMessageToUser(emailPush, mobilePush, smsPublish, newUserIdList, ds, corpId, request);
				}
			}else {
				failureMap.put("i18NCode", "oa.meeting.datadelsuccess");
				return OperationResult.buildFailureResult("发布失败",failureMap);
			}
		} catch (Exception e) {
			e.printStackTrace();
			failureMap.put("i18NCode", "oa.meeting.pushfalse");
			OperationResult.buildFailureResult("发布失败",failureMap);
		}
		failureMap.put("i18NCode", "oa.meeting.pushsucess");
		return OperationResult.buildSuccessResult("发布成功",failureMap);
    }
    
    /**
     * 发送消息通知
     * @param userIdList
     * @param ds
     * @param corpId
     * @param request
     */
    private void sendMessageToUser(boolean emailPush, boolean mobilePush, boolean smsPublish, List<String> userIdList, Map<String, Object> ds, String corpId, HttpServletRequest request) {
    	LOGGER.debug("-----sendMessageToUser--------");
    	StringBuffer ids = new StringBuffer();
		StringBuffer jsonIds = new StringBuffer("[");
		for(int i = 0; i < userIdList.size(); i++) {
			if(i == userIdList.size() - 1) {
				ids.append(userIdList.get(i));
				jsonIds.append("{\"10\":\"" + userIdList.get(i) + "\"}]");
			}else {
				ids.append(userIdList.get(i) + ",");
				jsonIds.append("{\"10\":\"" + userIdList.get(i) + "\"},");
			}
		}
		jsonIds.append("]");
		ds.put("userIds", ids.toString());
		ds.put("orgIds", "");
		ds.put("languageCode", request.getParameter("languageCode"));
		LOGGER.debug("---ids:"+ids);
		if(!"".equals(ids.toString())) {
			this.meetingSendMsgUtils.sendMail(ds, emailPush, corpId, TOKEN);
			this.meetingSendMsgUtils.sendMsgToApp(ds, mobilePush, corpId, TOKEN, request);
			this.meetingSendMsgUtils.sendSMS(ds, smsPublish, corpId, TOKEN);
		}
		if(!"[]".equals(jsonIds.toString())) this.meetingSendMsgUtils.sendMessage(ds, jsonIds.toString(), corpId, TOKEN);
    }
    
    /**
     * 判断会议信息是否修改
     * @param newEntity
     * @param addrListJson
     * @param corpId
     * @return
     */
    private boolean isEntityChanged(ApplyRecord newEntity, ApplyRecord oldEntity, String addrListJson, String corpId) {
    	List<SignedAddress> saOldList = this.signedAddressService.findByRecordId(newEntity.getId());
    	List<Map<String, String>> addrList = null;
		if(!"".equals(addrListJson)) {
			addrList = JsonUtils.readListValue(addrListJson);
		}
    	List<SignedAddress> saNewList = null;
    	if(CollectionUtils.isNotEmpty(addrList)) {
    		saNewList = new ArrayList<SignedAddress>();
    		for(Map<String, String> m : addrList) {
    			SignedAddress sa = new SignedAddress();
    			sa.setLongitude(m.get("lng"));
    			sa.setLatitude(m.get("lat"));
    			sa.setSignedAddress(m.get("address"));
    			saNewList.add(sa);
    		}
    	}
    	boolean sAddressIsSame = true;
    	if(CollectionUtils.isNotEmpty(saOldList) && CollectionUtils.isNotEmpty(saNewList)) {
    		if(!saOldList.equals(saNewList)) {
    			sAddressIsSame = false;
    		}
    	}else if((CollectionUtils.isEmpty(saOldList) && CollectionUtils.isNotEmpty(saNewList)) || 
    			(CollectionUtils.isNotEmpty(saOldList) && CollectionUtils.isEmpty(saNewList))){
    		sAddressIsSame = false;
    	}
    	//判断会议信息和签到地址是否一样
    	if(oldEntity.equals(newEntity) && sAddressIsSame) return false;
    	else return true;
    }
    
    /**
     * 流程提交之后处理字段
     *
     * @param entity
     * @param model
     * @return
     */
    @RequestMapping(value = "/editSaveAfterBpm", method = RequestMethod.POST)
    public OperationResult editSaveAfterBpm(Model model,HttpServletRequest request) {
        try {
			String id = StringUtils.null2String(request.getParameter("id"));
			String businessRecordId = StringUtils.null2String(request.getParameter("businessRecordId"));
			String nStatus = StringUtils.null2String(request.getParameter("status"));
			ApplyRecord entity = this.service.findOne(id);
			WebUser user = WebUtils.getCurrentUser();
			String corpId = user.getCorpId();
			if(StringUtils.isNotBlank(businessRecordId)) {
				entity.setBusinessRecordId(businessRecordId);
			}
			//状态修改
			int changeStatus = 0;//此为流程的状态 草稿：0,新建：1,驳回到发起节点:2,正常完成：3,非正常完成：4,撤销到发起节点：5, 正常通过: 6
			if("3".equals(nStatus)){//正常结束
				String startTime = entity.getStartTime();
				SimpleDateFormat sf  = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
				Date _startTime = sf.parse(startTime + ":00");
				Date now = new Date();
				if(_startTime.getTime() < now.getTime()) changeStatus = -1;
				else changeStatus = 1;
			}else if("2".equals(nStatus)){//驳回到发起人
			    changeStatus = 2;
			}else if("4".equals(nStatus) || "5".equals(nStatus)){//发起人撤销或非正常结束
			    changeStatus = -1;
			}else if("6".equals(nStatus) || "1".equals(nStatus)){//表单提交或新建
			    changeStatus = 0;
			}else if("0".equals(nStatus)){//草稿箱
			    changeStatus = 6;
			}
			entity.setStatus(changeStatus);//会议状态（0——申请中,1——未召开,2——已驳回,3——已取消,4——进行中,5——已结束,6——草稿箱）
			
			OperationResult result = null;
			if(entity.getIsSync() == 0) {
				result = super.editSave(entity);
				if(changeStatus == 1){
				    //保存周期会议
				    if(entity.getIsCycle() == 1) {
				    	List<Map<String, String>> cyclelist = this.service.getCycleDateList(entity);
				    	this.service.saveCycleMeeting(entity, cyclelist);
				    }
				}
			}else{
				
				 // 主持人
			    String emceeUserJsonStr = StringUtils.null2String(request.getParameter("jsonStrEmceeUser"));
			    String emceeUserName ="";
			    String emceeUser = StringUtils.null2String(entity.getEmceeUser());
			    if("".equals(emceeUserName)&&!"".equals(emceeUser)) {
			    	Map paramMap = new HashMap();
			        String sql = (new StringBuilder()).append("select name from ").append("oa_meeting_apply_record_scope").append(" where fieldDataTable = :fieldDataTable and fieldData = :fieldData and fieldDataValue= :fieldDataValue ").toString();
			        paramMap.put("fieldDataTable", "oa_meeting_apply_record");
			        paramMap.put("fieldData", "emcee_user");
			        paramMap.put("fieldDataValue", emceeUser);
			        List<Map<String,Object>> emceeUserList = this.popUserScopeUtilService.findByListNativeQuery(sql, "", paramMap);
			    	 if(emceeUserList!=null && emceeUserList.size()>0) {
			    		 emceeUserName=StringUtils.null2String(emceeUserList.get(0).get("name"));
			    	 }
			    }
			    if ("".equals(emceeUser)) {
			        emceeUser = UuidUtils.UUID();
			        entity.setEmceeUser(emceeUser);
			    }
			    if(!"undefined".equals(emceeUserJsonStr)){
			        this.popUserScopeUtilService.saveScopeData("oa_meeting_apply_record_scope", emceeUser, emceeUserJsonStr,
			                "oa_meeting_apply_record", "emcee_user");
			    }
			    // 纪要员
			    String memoUserJsonStr = StringUtils.null2String(request.getParameter("jsonStrMemoUser"));
			    String memoUser = StringUtils.null2String(entity.getMemoUser());
			    if ("".equals(memoUser)) {
			        memoUser = UuidUtils.UUID();
			        entity.setMemoUser(memoUser);
			    }
			    if(!"undefined".equals(memoUserJsonStr)) {
			        this.popUserScopeUtilService.saveScopeData("oa_meeting_apply_record_scope", memoUser, memoUserJsonStr,
			                "oa_meeting_apply_record", "memo_user");
			    }
			    // 参会人
			    String attendUserJsonStr = StringUtils.null2String(request.getParameter("jsonStrAttendUser"));
			    String attendUser = StringUtils.null2String(entity.getAttendUser());
			    if ("".equals(attendUser)) {
			        attendUser = UuidUtils.UUID();
			        entity.setAttendUser(attendUser);
			    }
			    if(!"undefined".equals(attendUserJsonStr)) {
			        this.popUserScopeUtilService.saveScopeData("oa_meeting_apply_record_scope", attendUser, attendUserJsonStr,
			                "oa_meeting_apply_record", "attend_user");
			    }
			    
			    // 会议列席人
			    String attendantsJsonStr = StringUtils.null2String(request.getParameter("jsonStrAttendants"));
			    String attendants = StringUtils.null2String(entity.getMeetingAttendants());
			    if ("".equals(attendants)) {
			    	attendants = UuidUtils.UUID();
			        entity.setMeetingAttendants(attendants);
			    }
			    if(!"undefined".equals(attendantsJsonStr)) {
			        this.popUserScopeUtilService.saveScopeData("oa_meeting_apply_record_scope", attendants, attendantsJsonStr,
			                "oa_meeting_apply_record", "meeting_attendants");
			    }
			    
			    //改变提醒方式默认值
				int isNotice = entity.getIsNotice();
				if(isNotice == 1){
				    entity.setNoticeType("2");
				}
				
				result = super.editSave(entity);

				//地址
				List<SignedAddress> list = this.signedAddressService.findByFkid(id);
				if(list!=null && list.size()>0){
				    for(int i=0; i<list.size(); i++){
				        SignedAddress address = list.get(i);
				        if(address!=null && StringUtils.isEmpty(address.getApplyRecordId())){
				            address.setApplyRecordId(address.getFkid());
				        }
				    }
				    this.signedAddressService.save(list);
				}
				
				if(changeStatus == 1){//会议流程正常结束，会议为未召开状态，发送推送消息
				    this.service.editSaveByStatus(entity,"1","",TOKEN);
				    //保存周期会议
				    if(entity.getIsCycle() == 1) {
				    	List<String> newUserIdList = this.service.getApplyRecordUserList(entity, TOKEN);
				    	List<Map<String, String>> cyclelist = this.service.getCycleDateList(entity);
				    	List<ApplyRecord> arCycleList = this.service.saveCycleMeeting(entity, cyclelist);
				    	CycleMeetingThread cycThread = new CycleMeetingThread(arCycleList, newUserIdList, entity.getId(), corpId, entity.getIsSigned());
				    	cycThread.start();
				    }
				    
				    //----全时会议处理--start
					int meetingWay = entity.getMeetingWay();
					LOGGER.debug("tMeetingWay："+meetingWay);

					boolean newIsWeb = false;
					if(meetingWay==1 || meetingWay==2) {
						newIsWeb = true;
					}
					LOGGER.debug("newIsWeb："+newIsWeb);

					if(newIsWeb) {
								
						//新增
						Map map = qsMeetingService.newQSMeeting(entity.getName(),
					                                            entity.getStartTime(),
					                                            entity.getEndTime(),
					                                            entity.getCreatedBy(),
					                                            user.getJwtToken());
						String success = map.get("success")+"";
						if("0".equals(success)) {

							QSMeetingInfo info = (QSMeetingInfo) map.get("info");
							//保存全时会议信息
							//String emceeUserId = this.service.getEmceeUser(entity);
							info.setMeetingApplyId(entity.getId());
							info.setEmceeUser(entity.getCreatedBy());
							qsMeetingService.saveQSMeetingInfo(info);
						}else {
							String msg = (String) map.get("msg");
							LOGGER.error(msg);
						}
	
					}
					//----全时会议处理--end

				    BoardroomSet room = null;
				    if(StringUtils.isNotEmpty(entity.getBoardroomId())) {
				    	room = this.boardroomSetService.findOne(entity.getBoardroomId());
				    }
				    int nStauts = entity.getStatus();
				    String userIds = "", jsonIds = "";
				    Map<String, Object> ds = new HashMap<>();
				    ds.put("applyRecordId", id);
				    ds.put("meetingTitle", entity.getName());
				    ds.put("startTime", entity.getStartTime());
				    ds.put("endTime", entity.getEndTime());
				    ds.put("emceeUserName", emceeUserName);
				    ds.put("boardroom", room == null ? (StringUtils.isNotEmpty(entity.getAddress()) ? entity.getAddress():"无") : room.getAddress());
				    String noticeUserId = entity.getCreatedBy();
				    String userName = "";
				    if(StringUtils.isNotEmpty(noticeUserId)){
				        Map<String, Object> userInfo = this.userApiService.getUser(noticeUserId, corpId,  "", TOKEN);
				        if(userInfo != null){
				            userName = StringUtils.null2String(userInfo.get("userName"));
				        }
				    }
				    ds.put("userId", noticeUserId);
				    ds.put("userName", userName);
				    ds.put("userOrg", entity.getCreatedOrg());
				    if(nStauts == 1){
				        ds.put("type", "2");
				        List<String> userIdList = this.service.getApplyRecordUserList(entity, TOKEN);
						if(CollectionUtils.isNotEmpty(userIdList)){
							StringBuffer idsBuffer = new StringBuffer();
							StringBuffer jsonIdsBuffer = new StringBuffer("[");
							for(int i = 0; i < userIdList.size(); i++) {
								if(i == userIdList.size() - 1) {
									idsBuffer.append(userIdList.get(i));
									jsonIdsBuffer.append("{\"10\":\"" + userIdList.get(i) + "\"}]");
								}else {
									idsBuffer.append(userIdList.get(i) + ",");
									jsonIdsBuffer.append("{\"10\":\"" + userIdList.get(i) + "\"},");
								}
							}
							jsonIdsBuffer.append("]");
							userIds = idsBuffer.toString();
							jsonIds = jsonIdsBuffer.toString();
						}
				    }
				    
				    if(!StringUtils.isEmpty(userIds)){
				    	boolean mobilePush = false;
				        boolean emailPush = false;
				        boolean smsPublish = false;
						String mesgPush = entity.getMessagePush();
						if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("mobile")) mobilePush = true;
						if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("email")) emailPush = true;
						if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("sms")) smsPublish = true;
				        ds.put("userIds", userIds);
				        ds.put("orgIds", "");
				        this.meetingSendMsgUtils.sendMail(ds, emailPush, corpId, TOKEN);
				        this.meetingSendMsgUtils.sendMsgToApp(ds, mobilePush, corpId, TOKEN, request);
						this.meetingSendMsgUtils.sendSMS(ds, smsPublish, corpId, TOKEN);
				    }
				    if(StringUtils.isNotEmpty(jsonIds) && !"[]".equals(jsonIds.toString())){
				        this.meetingSendMsgUtils.sendMessage(ds, jsonIds, corpId, TOKEN);
				    }
				}
				return result;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
        return OperationResult.buildFailureResult("处理失败");
    }

    /**
     * 判断时间段内是否已存在会议
     * @param request
     * @return
     */
    @RequestMapping(value = "/validateMeetingTime", method = RequestMethod.GET)
    public OperationResult validateMeetingTime(HttpServletRequest request) {
        String id = StringUtils.null2String(request.getParameter("id"));
        WebUser user = WebUtils.getCurrentUser();
        String corpId = user.getCorpId();
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        String boardroomId = request.getParameter("boardroomId");
        String isCycle = request.getParameter("isCycle");
        //验证会议开始结束时间是否在会议室的范围内
//        Date start = DateUtils.parseDate(startTime);
//        Date end = DateUtils.parseDate(endTime);
//        if(start.getTime() == end.getTime()){
            msg = this.boardroomSetService.checkTime(boardroomId,startTime, endTime,corpId);
            if (StringUtils.isNotEmpty(msg)) {
                return OperationResult.buildFailureResult(msg);
            }
//        }
        //验证会议室在会议开始结束时间范围内是否已有会议
        msg = this.service.checkApplyRecordDate(id,startTime, endTime,boardroomId, corpId);
        if (StringUtils.isNotEmpty(msg)) {
            return OperationResult.buildFailureResult(msg);
        }
        
        //检测该会议室再周期内是否被占用
        if("1".equals(isCycle)) {
        	ApplyRecord entity = new ApplyRecord();
        	String cycleType = request.getParameter("cycleType");
            entity.setStartTime(startTime);
            entity.setEndTime(endTime);
            entity.setBoardroomId(boardroomId);
            entity.setIsCycle(Integer.parseInt(isCycle));
        	entity.setCycleType(Integer.parseInt(cycleType));
        	entity.setCycleValue(request.getParameter("cycleValue"));
        	entity.setCycleEndTime(request.getParameter("cycleEndTime"));
        	List<Map<String, String>> cyclelist = this.service.getCycleDateList(entity);
        	msg = this.service.checkCycleApplyRecordDate(entity, cyclelist, corpId);
        	if (StringUtils.isNotEmpty(msg)) return OperationResult.buildFailureResult(msg);
        }
        return OperationResult.buildSuccessResult();
    }
    
    /**
     * 编辑页面
     * 
     * @param model
     * @return
     */
    @RequestMapping(value = "/editShow", method = RequestMethod.GET)
    public OperationResult editShow(HttpServletRequest request) {
    	Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
			WebUser user = WebUtils.getCurrentUser();
			String corpId = user.getCorpId();
			String id = ValidateUtils.filter(request.getParameter("id"));
			ApplyRecord applyRecord = this.service.findOne(id);
			if(applyRecord == null) return OperationResult.buildFailureResult("当前数据已删除");
			resultMap.put("entity", applyRecord);
			String boardroomName = "", limitDate = "";
			String roomId = applyRecord.getBoardroomId();
			if(StringUtils.isNotEmpty(roomId)) {
            	BoardroomSet room = this.boardroomSetService.findOne(roomId);
            	
                if(room != null) {
                	boardroomName = room.getName();
                	limitDate = this.boardroomSetService.getLimitDate(room.getBeforeDays());
                	//查询是否是审批的会议
                	resultMap.put("isApprove",room.getIsApprove());
                }
            }
			resultMap.put("boardroomName", boardroomName);
			resultMap.put("limitDate", limitDate);
			// 主持人
            String emceeUser = popUserScopeUtilService.getScopeTypeValue("oa_meeting_apply_record_scope", "oa_meeting_apply_record",
                    "emcee_user", StringUtils.null2String(applyRecord.getEmceeUser()));
            resultMap.put("emceeUser", emceeUser);
            if (StringUtils.isNotEmpty(emceeUser)) {
                String scopeName = this.userApiService.getScopeName(emceeUser, corpId, TOKEN);
                resultMap.put("emceeUserName", scopeName);
            }
            // 纪要员
            String memoUser = popUserScopeUtilService.getScopeTypeValue("oa_meeting_apply_record_scope", "oa_meeting_apply_record",
                    "memo_user", StringUtils.null2String(applyRecord.getMemoUser()));
            resultMap.put("memoUser", memoUser);
            if (StringUtils.isNotEmpty(memoUser)) {
                String scopeName = this.userApiService.getScopeName(memoUser, corpId, TOKEN);
                resultMap.put("memoUserName", scopeName);
            }
            // 参会人
            String attendUser = popUserScopeUtilService.getScopeTypeValue("oa_meeting_apply_record_scope", "oa_meeting_apply_record",
                    "attend_user", StringUtils.null2String(applyRecord.getAttendUser()));
            resultMap.put("attendUser", attendUser);
            if (StringUtils.isNotEmpty(attendUser)) {
            	String scopeName = this.userApiService.getScopeName(attendUser, corpId, TOKEN);
            	resultMap.put("attendUserName", scopeName);
            }
            //会议列席人
            String recordAttendants=StringUtils.null2String(applyRecord.getMeetingAttendants());
            String attendants = popUserScopeUtilService.getScopeTypeValue("oa_meeting_apply_record_scope",
                    "oa_meeting_apply_record", "meeting_attendants", recordAttendants);
            resultMap.put("attendants", attendants);
            if (StringUtils.isNotEmpty(attendants)) {
            	String scopeName = service.getScopeName("oa_meeting_apply_record", recordAttendants, "meeting_attendants");
            	resultMap.put("attendantsName", scopeName);
            }
            
            resultMap.put("hidApplyRecordDate", DateUtils.formatDate(DateUtils.now()));
            String applyStartDate = "", applyEndDate = "";
            String selectStartTime = "", selectEndTime= "";
            String startTime = applyRecord.getStartTime();
            if(StringUtils.isNotEmpty(startTime)){
                applyStartDate = startTime.substring(0,10);
                selectStartTime = startTime.substring(11,16);
            }
            String endTime = applyRecord.getEndTime();
            if(StringUtils.isNotEmpty(endTime)){
            	applyEndDate = endTime.substring(0,10);
                selectEndTime = endTime.substring(11,16);
            }
            resultMap.put("applyStartDate",  applyStartDate);
            resultMap.put("applyEndDate",  applyEndDate);
            resultMap.put("selectStartTime", selectStartTime);
            resultMap.put("selectEndTime", selectEndTime);
            //签到地址
            List<SignedAddress> address = this.signedAddressService.findByRecordId(id);
            resultMap.put("address", address);
            String noticeType = commonService.getSysParamValueByMark(corpId, user.getJwtToken(),"sysImType");
            resultMap.put("noticeType", noticeType);
            String messagePushSW = commonService.getMessagePush(corpId, user.getJwtToken(),"meeting");
            resultMap.put("messagePushSW", messagePushSW);
            resultMap.put("meetingTypes", meetingTypeService.getMeetingTypes(corpId));
            //塞入附件信息
            resultMap.put("fileList", service.getAttachmentName(applyRecord.getFileId()));
            
        } catch (Exception e) {
			e.printStackTrace();
			return OperationResult.buildFailureResult("服务端错误");
		}
        return OperationResult.buildSuccessResult(resultMap);
    }

    /**
     * 预约会议室流程结束后判断是否可发起会议或是否可取消预约会议室
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/canCancelMeeting", method = RequestMethod.GET)
    public String canCancelMeeting(HttpServletRequest request) {
        String id = ValidateUtils.filter(request.getParameter("id"));
        String result = "0";//不可取消会议
        if (StringUtils.isNotEmpty(id)) {
            ApplyRecord applyRecord = this.service.findOne(id);
            if(applyRecord != null){
                int status = applyRecord.getStatus();
                if(status == 1){//可取消会议
                    result = "1";
                }
            }
        }
        return result;
    }

    /**
     * 预约会议室流程结束后判断是否已经发起过会议
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/editShowAfterBpm", method = RequestMethod.GET)
    public Map<String, Object> editShowAfterBpm(HttpServletRequest request) {
        WebUser user = WebUtils.getCurrentUser();
        String corpId = "";
        //选择日期
        String applyStartDate = "", applyEndDate = "";
        if (user != null) {
            corpId = user.getCorpId();
        }
        String id = ValidateUtils.filter(request.getParameter("id"));
        Map<String, Object> result = new HashMap<>();

        if (StringUtils.isNotEmpty(id)) {
            ApplyRecord applyRecord = this.service.findOne(id);
            result.put("entity", applyRecord);

            String startTime = applyRecord.getStartTime();
            if(StringUtils.isNotEmpty(startTime)){
                applyStartDate = startTime.substring(0,16);
            }
            String endTime = applyRecord.getEndTime();
            if(StringUtils.isNotEmpty(endTime)){
                applyEndDate = endTime.substring(0,16);
            }

            //会议室名称
            String roomId = applyRecord.getBoardroomId();
            BoardroomSet room = this.boardroomSetService.findOne(roomId);
            if(room != null){
                result.put("boardroomName", room.getName());
            }
            result.put("boardRoom", room);
            //会议服务名称
            String serveIds = applyRecord.getMeetingServe();
            String servesName = "";
            if(StringUtils.isNotEmpty(serveIds)){
                List<ServeSet> serveSets = this.serveSetService.getServeSetListByIds(serveIds);
                for (ServeSet set: serveSets) {
                    if(set != null){
                        servesName += set.getName() + ",";
                    }
                }
                if(StringUtils.isNotEmpty(servesName)){
                    servesName = servesName.substring(0, servesName.length()-1);
                }
            }
            result.put("servesName", servesName);
        } else {
            result.put("entity", new ApplyRecord());
        }

        String userId = user.getUserId();
        result.put("defaultEmceeUser", "userSCOPE"+userId);//默认主持人
        result.put("defaultEmceeName", user.getCnName());//默认主持人

        result.put("applyStartDate",  applyStartDate);
        result.put("applyEndDate",  applyEndDate);

        // 查询基础设置
//        String noticeType = "";
//        BaseSet baseSet = this.baseSetService.getBaseSetInfo(corpId);
//        if (baseSet != null) {
//            noticeType = baseSet.getNoticeType();
//        }
        String noticeType = commonService.getSysParamValueByMark(corpId, user.getJwtToken(),"sysImType");
        result.put("noticeType", noticeType);

        return result;
    }
    
    //获取消息推送base端设置
    @RequestMapping(value = "/getPushMessageSW", method = RequestMethod.GET)
    public String getPushMessageSW(HttpServletRequest request) {
        WebUser user = WebUtils.getCurrentUser();
        return commonService.getMessagePush(user.getCorpId(), user.getJwtToken(),"meeting");
    }
    
    /**
     * 查看页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/viewShow", method = RequestMethod.GET)
    public Map<String, Object> viewShow(HttpServletRequest request) {
        WebUser user = WebUtils.getCurrentUser();
        String userId = user.getUserId();
        String corpId = "";
        if (user != null) {
            corpId = user.getCorpId();
        }
        String id = ValidateUtils.filter(request.getParameter("id"));
        Map<String, Object> result = new HashMap<>();
        
        ApplyRecord applyRecord = this.service.findOne(id);
        if(applyRecord == null) {//对象是否删除
        	result.put("entityIsDelete", true);
        }else {
        	result.put("entityIsDelete", false);
        	result.put("currentUserId", user.getUserId());
        	result.put("entity", applyRecord);
            if(StringUtils.isNotEmpty(applyRecord.getMeetingTypeId())) {
            	MeetingType mt = meetingTypeService.findOne(applyRecord.getMeetingTypeId());
            	if(mt != null) result.put("meetingType", mt.getTypeName());
            }
            String boardroomName = "";
            if(StringUtils.isNotEmpty(applyRecord.getBoardroomId())) {
            	//会议室查询
                BoardroomSet boardroomSet = this.boardroomSetService.findOne(applyRecord.getBoardroomId());
                if(boardroomSet!=null){
                    boardroomName = boardroomSet.getName();
                    result.put("meetingAddress", boardroomSet.getAddress());
                }
            }else {
            	boardroomName = applyRecord.getAddress();
            }
            result.put("boardroomName", boardroomName);
            if(StringUtils.isEmpty(applyRecord.getBoardroomId())) {
            	result.put("meetingAddress", applyRecord.getAddress());
            }
            String isCreateUser = "0";//是否是创建人 0：否  1：是
        	String isEmceeUser = "0";//是否是主持人 0：否  1：是
        	//发起人
			String createdBy = applyRecord.getCreatedBy();
			if(createdBy.equals(userId)){//是否是发起人
				isCreateUser = "1";
			}
			result.put("isCreateUser", isCreateUser);
			
            // 主持人
			String recordEmceeUser=StringUtils.null2String(applyRecord.getEmceeUser());
            String emceeUser = popUserScopeUtilService.getScopeTypeValue("oa_meeting_apply_record_scope",
                    "oa_meeting_apply_record", "emcee_user", recordEmceeUser);
            result.put("emceeUser", emceeUser);
            List<String> scopeValues = popUserScopeUtilService.getScopeValue("oa_meeting_apply_record_scope", "oa_meeting_apply_record", "emcee_user", recordEmceeUser);
			if(CollectionUtils.isNotEmpty(scopeValues) && scopeValues.size() > 0 && scopeValues.get(0).equals(userId)){
				isEmceeUser = "1";
			}
			result.put("isEmceeUser", isEmceeUser);
            result.put("emceeUserId", "");
            if (StringUtils.isNotEmpty(emceeUser)) {
//                String scopeName = this.userApiService.getScopeName(emceeUser, corpId, TOKEN);
            	String scopeName = service.getScopeName("oa_meeting_apply_record", recordEmceeUser, "emcee_user");
                result.put("emceeUserName", scopeName);
                String[] scope = emceeUser.split("SCOPE");
                if(scope.length > 1){
                	result.put("emceeUserId", scope[1]);
                }
            }
            
            // 纪要员
            String recordMemoUser=StringUtils.null2String(applyRecord.getMemoUser());
            String memoUser = popUserScopeUtilService.getScopeTypeValue("oa_meeting_apply_record_scope",
                    "oa_meeting_apply_record", "memo_user", recordMemoUser);
            result.put("memoUser", memoUser);
            if (StringUtils.isNotEmpty(memoUser)) {
//                String scopeName = this.userApiService.getScopeName(memoUser, corpId, TOKEN);
                String scopeName = service.getScopeName("oa_meeting_apply_record", recordMemoUser, "memo_user");
                result.put("memoUserName", scopeName);
            }
            
            //参会人
            String recordAttendUser=StringUtils.null2String(applyRecord.getAttendUser());
            String attendUser = popUserScopeUtilService.getScopeTypeValue("oa_meeting_apply_record_scope",
                    "oa_meeting_apply_record", "attend_user", recordAttendUser);
            result.put("attendUser", attendUser);
            if (StringUtils.isNotEmpty(attendUser)) {
//                String scopeName = this.userApiService.getScopeName(attendUser, corpId, TOKEN);
            	String scopeName = service.getScopeName("oa_meeting_apply_record", recordAttendUser, "attend_user");
                result.put("attendUserName", scopeName);
            }
            
            //会议列席人
            String recordAttendants=StringUtils.null2String(applyRecord.getMeetingAttendants());
            String attendants = popUserScopeUtilService.getScopeTypeValue("oa_meeting_apply_record_scope",
                    "oa_meeting_apply_record", "meeting_attendants", recordAttendants);
            result.put("attendants", attendants);
            if (StringUtils.isNotEmpty(attendants)) {
            	String scopeName = service.getScopeName("oa_meeting_apply_record", recordAttendants, "meeting_attendants");
                result.put("attendantsName", scopeName);
            }
            
            String meetingServe = "";
            if(StringUtils.isNotEmpty(applyRecord.getMeetingServe())){
                List<ServeSet> serveSetList = this.serveSetService.getServeSetListByIds(applyRecord.getMeetingServe());
                if(serveSetList!=null && serveSetList.size()>0){
                    for(ServeSet s : serveSetList){
                        meetingServe += s.getName() + ",";
                    }
                    meetingServe = meetingServe.substring(0,meetingServe.length()-1);
                }
            }
            result.put("meetingServe", meetingServe);
            
            //签到地址
            List<SignedAddress> address = this.signedAddressService.findByRecordId(id);
            result.put("address", address);
            
            //查询基础设置
//            String noticeType = "";
//            BaseSet baseSet = this.baseSetService.getBaseSetInfo(corpId);
//            if(baseSet!=null){
//                noticeType = baseSet.getNoticeType();
//            }
            String noticeType = commonService.getSysParamValueByMark(corpId, user.getJwtToken(),"sysImType");
            result.put("noticeType", noticeType);
            String qrcodeUrl = "";
            String qrCodeAttachId = applyRecord.getQrcodeAttach();
			if(StringUtils.isNotEmpty(qrCodeAttachId)){
				List<Map<String, String>> images = this.attachmentUtilsService.getAttachmentByIds(qrCodeAttachId, corpId, TOKEN);
				if(images!=null && images.size()>0){
					Map<String, String> image = images.get(0);
					String url = GlobalConstant.getFlexServerPath(request);
					//qrcodeUrl = url + image.get("imageUrl");
					qrcodeUrl = url + image.get("downloadUrl");
					qrcodeUrl =qrcodeUrl.replace("/download?", "/image?");
				}
			}
			result.put("image", qrcodeUrl);
			//塞入附件信息
	        result.put("fileList", service.getAttachmentName(applyRecord.getFileId()));
        }
        
        return result;
    }

    /**
     * 流程中申请记录查看
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/viewShowProgress", method = RequestMethod.GET)
    public Map<String, Object> viewShowProgress(HttpServletRequest request) {
        String id = ValidateUtils.filter(request.getParameter("meetingId"));
        Map<String, Object> result = new HashMap<>();
        ApplyRecord applyRecord = this.service.findOne(id);
        result.put("isSync", applyRecord.getIsSync());
        //会议室查询
        String boardroomName = "";
        BoardroomSet boardroomSet = this.boardroomSetService.findOne(applyRecord.getBoardroomId());
        if(boardroomSet!=null){
            boardroomName = boardroomSet.getName();
        }
        result.put("boardroomName", boardroomName);

        //会议服务
        String meetingServe = "";
        if(StringUtils.isNotEmpty(applyRecord.getMeetingServe())){
            List<ServeSet> serveSetList = this.serveSetService.getServeSetListByIds(applyRecord.getMeetingServe());
            if(serveSetList!=null && serveSetList.size()>0){
                for(ServeSet s : serveSetList){
                    meetingServe += s.getName() + ",";
                }
                meetingServe = meetingServe.substring(0,meetingServe.length()-1);
            }
        }
        result.put("meetingServe", meetingServe);

        WebUser user = WebUtils.getCurrentUser();
        String corpId = user.getCorpId();

        // 主持人
        String emceeUser = popUserScopeUtilService.getScopeTypeValue("oa_meeting_apply_record_scope",
                "oa_meeting_apply_record", "emcee_user", StringUtils.null2String(applyRecord.getEmceeUser()));
        result.put("emceeUser", emceeUser);
        result.put("emceeUserId", "");
        if (StringUtils.isNotEmpty(emceeUser)) {
            String scopeName = this.userApiService.getScopeName(emceeUser, corpId, TOKEN);
            result.put("emceeUserName", scopeName);
            String[] scope = emceeUser.split("SCOPE");
            if(scope.length > 1){
                result.put("emceeUserId", scope[1]);
            }
        }else {
        	result.put("emceeUserName", "");
        }

        // 纪要员
        String memoUser = popUserScopeUtilService.getScopeTypeValue("oa_meeting_apply_record_scope",
                "oa_meeting_apply_record", "memo_user", StringUtils.null2String(applyRecord.getMemoUser()));
        result.put("memoUser", memoUser);
        result.put("memoUserName", "");
        if (StringUtils.isNotEmpty(memoUser)) {
            String scopeName = this.userApiService.getScopeName(memoUser, corpId, TOKEN);
            result.put("memoUserName", scopeName);
        }


        //参会人
        String attendUser = popUserScopeUtilService.getScopeTypeValue("oa_meeting_apply_record_scope",
                "oa_meeting_apply_record", "attend_user", StringUtils.null2String(applyRecord.getAttendUser()));
        result.put("attendUser", attendUser);
        result.put("attendUserName", "");
        if (StringUtils.isNotEmpty(attendUser)) {
            String scopeName = this.userApiService.getScopeName(attendUser, corpId, TOKEN);
            result.put("attendUserName", scopeName);
        }
        
      //参会人
        String attendants = popUserScopeUtilService.getScopeTypeValue("oa_meeting_apply_record_scope",
                "oa_meeting_apply_record", "meeting_attendants", StringUtils.null2String(applyRecord.getMeetingAttendants()));
        result.put("attendants", attendants);
        result.put("attendantsName", "");
        if (StringUtils.isNotEmpty(attendants)) {
            String scopeName = this.userApiService.getScopeName(attendants, corpId, TOKEN);
            result.put("attendantsName", scopeName);
        }

        return result;
    }
    
    /**
     * 删除（批量）数据
     * @param ids
     * @return
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public OperationResult delete(@RequestParam("ids") String... ids) {
    	WebUser user = WebUtils.getCurrentUser();
    	String corpId = user.getCorpId();
    	List<String> dataIds = new ArrayList<String>();
    	//删除关联的scope
    	List<String> attendUser = new ArrayList<>();
    	List<String> emceeUser = new ArrayList<>();
    	List<String> memoUser = new ArrayList<>();
    	for (String id : ids) {
    		ApplyRecord record = this.service.findOne(id);
			if(record == null) continue;
    		dataIds.add(id);
    		List<String> taskIds = meetingTaskInfoService.findTaskInfoIdsByApplyRecordIds(id);
    		if(CollectionUtils.isNotEmpty(taskIds)) dataIds.addAll(taskIds);
			if(record.getAttendUser() != null) attendUser.add(record.getAttendUser());
			if(record.getEmceeUser() != null) emceeUser.add(record.getEmceeUser());
			if(record.getMemoUser() != null) memoUser.add(record.getMemoUser());
		}
    	this.popUserScopeUtilService.delScopeMethod("oa_meeting_apply_record_scope", attendUser, "oa_meeting_apply_record", "attend_user");
    	this.popUserScopeUtilService.delScopeMethod("oa_meeting_apply_record_scope", emceeUser, "oa_meeting_apply_record", "emcee_user");
    	this.popUserScopeUtilService.delScopeMethod("oa_meeting_apply_record_scope", memoUser, "oa_meeting_apply_record", "memo_user");
    	
    	//删除相关签到信息
    	this.signedInfoService.deleteSignInfo(ids);
    	//删除相关定位签到地址信息
    	this.signedAddressService.deleteSignAddress(ids);
    	//删除相关通知
    	this.noticeInfoService.deleteByApplyrecord(ids);
    	//删除相关通知
    	this.noticeTurnoverService.deleteByApplyrecordId(ids);
    	//删除相关会议纪要
    	this.memoInfoService.deleteMemoInfo(ids);
    	//删除相关会议任务
    	this.meetingTaskInfoService.deleteByRecordId(ids);
    	//删除相关会议消息
    	this.meetingSendMsgUtils.deleteMessage(dataIds, corpId, TOKEN);
    	
    	//取消全时会议
    	this.qsMeetingService.delQSMeetings(user.getJwtToken(),ids);
		//删除全时会议记录
		this.qsMeetingService.deleteByRecordId(ids);
		
    	return super.delete(ids);
    }
    
    /**
     * 删除（批量）周期会议数据
     */
    @RequestMapping(value = "/deleteCycleMeeting", method = RequestMethod.POST)
    @Transactional
    public OperationResult deleteCycleMeeting(@RequestParam("ids") String... ids) {
    	WebUser user = WebUtils.getCurrentUser();
    	String corpId = StringUtils.null2String(user.getCorpId());
    	long time=System.currentTimeMillis();
    	LOGGER.debug("-----zhaozy1:"+(System.currentTimeMillis()-time));
		time=System.currentTimeMillis();
    	List<String> list = service.getCycleMeetingids(Arrays.asList(ids));
    	LOGGER.debug("-----zhaozy2:"+(System.currentTimeMillis()-time));
		time=System.currentTimeMillis();
    	if(CollectionUtils.isEmpty(list)) return OperationResult.buildSuccessResult("删除成功");
    	List<String> dataIds = new ArrayList<String>();
    	//删除关联的scope
    	List<String> attendUser = new ArrayList<>();
    	List<String> emceeUser = new ArrayList<>();
    	List<String> memoUser = new ArrayList<>();
    	String[] deleteIds = new String[list.size()];
    	ApplyRecord record = null;
    	List<String> taskIds = null;
    	String id = "";
    	LOGGER.debug("-----zhaozy3:"+(System.currentTimeMillis()-time));
		time=System.currentTimeMillis();
    	for (int i = 0; i < list.size(); i++) {
    		id = list.get(i);
    		record = this.service.findOne(id);
    		if(record == null) continue;
    		deleteIds[i] = id;
    		dataIds.add(id);
    		taskIds = meetingTaskInfoService.findTaskInfoIdsByApplyRecordIds(id);
    		if(CollectionUtils.isNotEmpty(taskIds)) dataIds.addAll(taskIds);
			if(record.getAttendUser() != null) attendUser.add(record.getAttendUser());
			if(record.getEmceeUser() != null) emceeUser.add(record.getEmceeUser());
			if(record.getMemoUser() != null) memoUser.add(record.getMemoUser());
		}
    	LOGGER.debug("-----zhaozy4:"+(System.currentTimeMillis()-time));
		time=System.currentTimeMillis();
    	this.popUserScopeUtilService.delScopeMethod("oa_meeting_apply_record_scope", attendUser, "oa_meeting_apply_record", "attend_user");
    	this.popUserScopeUtilService.delScopeMethod("oa_meeting_apply_record_scope", emceeUser, "oa_meeting_apply_record", "emcee_user");
    	this.popUserScopeUtilService.delScopeMethod("oa_meeting_apply_record_scope", memoUser, "oa_meeting_apply_record", "memo_user");
    	LOGGER.debug("-----zhaozy5:"+(System.currentTimeMillis()-time));
		time=System.currentTimeMillis();
		String[] sqls=new String[5];
    	//删除相关签到信息
		sqls[0]="delete from oa_meeting_signed_info where "+MeetingUtils.getWhereInValuesSql("apply_record_id", Arrays.asList(deleteIds), 1000);
//    	this.signedInfoService.deleteSignInfo(deleteIds);
    	//删除相关定位签到地址信息
    	sqls[1]="delete from oa_meeting_signed_addr where "+MeetingUtils.getWhereInValuesSql("apply_record_id", Arrays.asList(deleteIds), 1000);
//    	this.signedAddressService.deleteSignAddress(deleteIds);
    	//删除相关通知
    	sqls[2]="delete from oa_meeting_notice_info where "+MeetingUtils.getWhereInValuesSql("apply_record_id", Arrays.asList(deleteIds), 1000);
//    	this.noticeInfoService.deleteByApplyrecord(deleteIds);
    	//删除相关邀请
    	sqls[3]="delete from oa_meeting_notice_turnover where "+MeetingUtils.getWhereInValuesSql("apply_record_id", Arrays.asList(deleteIds), 1000);
//    	this.noticeTurnoverService.deleteByApplyrecordId(deleteIds);
    	LOGGER.debug("-----zhaozy6:"+(System.currentTimeMillis()-time));
    	time=System.currentTimeMillis();
    	//删除相关会议纪要
    	this.memoInfoService.deleteMemoInfo(deleteIds);
    	LOGGER.debug("-----zhaozy7:"+(System.currentTimeMillis()-time));
    	time=System.currentTimeMillis();
    	//删除相关会议任务
    	sqls[4]="delete from oa_meeting_task_info where "+MeetingUtils.getWhereInValuesSql("apply_record_id", Arrays.asList(deleteIds), 1000);
//    	this.meetingTaskInfoService.deleteByRecordId(deleteIds);
    	LOGGER.debug("-----zhaozy8:"+(System.currentTimeMillis()-time));
    	time=System.currentTimeMillis();
    	// 删除相关会议消息
		MeetingUtils.execute(() -> {
			this.meetingSendMsgUtils.deleteMessage(dataIds, corpId, TOKEN);
		});
    	
    	LOGGER.debug("-----zhaozy9:"+(System.currentTimeMillis()-time));
		time=System.currentTimeMillis();
		JdbcTemplate jdbcTemplate=new JdbcTemplate(datasource);
		jdbcTemplate.batchUpdate(sqls);
		LOGGER.debug("-----zhaozy10:"+(System.currentTimeMillis()-time));
		time=System.currentTimeMillis();
        return super.delete(deleteIds);
    }
    
    /**
     * 修改会议状态
     */
    @RequestMapping(value = "/editSaveByStatus", method = RequestMethod.POST)
    public OperationResult editSaveByStatus(@ModelAttribute("entity") ApplyRecord entity, Model model,HttpServletRequest request) {
    	Map failureMap = new HashMap();
		try {
			WebUser webUser = WebUtils.getCurrentUser();
			String corpId = webUser.getCorpId();
			String nStatus = ValidateUtils.filter(request.getParameter("nStatus"));
			
			String messagePush=ValidateUtils.filter(Arrays.toString(request.getParameterValues("messagePushCheck")));
			String remindContent=ValidateUtils.filter(request.getParameter("remindContent"));
			int status = entity.getStatus();
			String id = StringUtils.null2String(entity.getId());
			if(status!=0 && ("1".equals(nStatus)||"2".equals(nStatus))){
				failureMap.put("i18NCode", "oa.meeting.meetapp");
				return OperationResult.buildFailureResult("该会议已审批",failureMap);
			}
			if(status == 3){
				failureMap.put("i18NCode", "oa.meeting.meetcancel");
				return OperationResult.buildFailureResult("该会议已取消",failureMap);
			}
			if("3".equals(nStatus) && status==1){
				List<String> taskIds = meetingTaskInfoService.findTaskInfoIdsByApplyRecordIds(id);
				//取消会议前删除会议相关任务
			    this.meetingTaskInfoService.deleteByRecordId(id);
			    //删除相关会议消息
				this.meetingSendMsgUtils.deleteMessage(taskIds, corpId, TOKEN);
				//释放会议室
//				if(StringUtils.isNotBlank(entity.getBoardroomId())) {
//					service.saveNewBoardRoomApply(entity);
//				}
			}
			OperationResult result = this.service.editSaveByStatus(entity,nStatus,"changeStatus",TOKEN);
			BoardroomSet room = null;
			if(StringUtils.isNotEmpty(entity.getBoardroomId())) {
				room = this.boardroomSetService.findOne(entity.getBoardroomId());
			}
			if(("1".equals(nStatus)&& status==0) || "3".equals(nStatus)){
				Map<String, Object> ds = new HashMap<>();
				if("1".equals(nStatus)){
					ds.put("type", "2");
				}else{
					ds.put("type", "3");
				}
				
				ds.put("status", status);
				ds.put("reason", entity.getReason());
				ds.put("applyRecordId", entity.getId());
				ds.put("meetingTitle", entity.getName());
				ds.put("startTime", entity.getStartTime());
				ds.put("endTime", entity.getEndTime());
				ds.put("boardroom", room == null ? (StringUtils.isNotEmpty(entity.getAddress()) ? entity.getAddress():"无") : room.getAddress());
				String noticeUserId = entity.getCreatedBy();
				ds.put("userId", noticeUserId);
				Map<String, Object> user =  this.userApiService.getUser(noticeUserId, corpId, "", TOKEN);
				String userName = StringUtils.null2String(user.get("userName"));
				ds.put("userName", userName);
				ds.put("userOrg", entity.getCreatedOrg());
				String ids = "", jsonIds = "[";
				List<String> userIdList = this.service.getApplyRecordUserList(entity, TOKEN);
				if(CollectionUtils.isNotEmpty(userIdList)){
					StringBuffer idsBuffer = new StringBuffer();
					StringBuffer jsonIdsBuffer = new StringBuffer("[");
					for(int i = 0; i < userIdList.size(); i++) {
						if(i == userIdList.size() - 1) {
							idsBuffer.append(userIdList.get(i));
							jsonIdsBuffer.append("{\"10\":\"" + userIdList.get(i) + "\"}]");
						}else {
							idsBuffer.append(userIdList.get(i) + ",");
							jsonIdsBuffer.append("{\"10\":\"" + userIdList.get(i) + "\"},");
						}
					}
					jsonIdsBuffer.append("]");
					ids = idsBuffer.toString();
					jsonIds = jsonIdsBuffer.toString();
				}
				
				if(!StringUtils.isEmpty(ids)){
					boolean mobilePush = false;
			        boolean emailPush = false;
			        boolean smsPublish = false;
					String mesgPush = messagePush;//entity.getMessagePush();
					if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("mobile")) mobilePush = true;
					//默认能发送邮件
					emailPush = true;
//					if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("email")) emailPush = true;
					if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("sms")) smsPublish = true;
					ds.put("userIds", ids);
					ds.put("orgIds", "");
					ds.put("customMessage", remindContent);
					this.meetingSendMsgUtils.sendMail(ds, emailPush, corpId, TOKEN);
					this.meetingSendMsgUtils.sendMsgToApp(ds, mobilePush, corpId, TOKEN, request);
					this.meetingSendMsgUtils.sendSMS(ds, smsPublish, corpId, TOKEN);
				}
			    if(StringUtils.isNotEmpty(jsonIds) && !"[]".equals(jsonIds)){
			        this.meetingSendMsgUtils.sendMessage(ds, jsonIds, corpId, TOKEN);
			    }
			}
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			failureMap.put("i18NCode", "oa.meeting.cancalfalse");
			return OperationResult.buildFailureResult("操作失败",failureMap);
		}
    }

    /**
     * 修改会议状态--(流程)
     */
    @RequestMapping(value = "/editSaveByBpmStatus", method = RequestMethod.POST)
    public OperationResult editSaveByBpmStatus(@ModelAttribute("id") String id, Model model,HttpServletRequest request) {
    	Map failureMap = new HashMap();
        if(StringUtils.isNotEmpty(id)){
            String nStatus = ValidateUtils.filter(request.getParameter("status"));
            ApplyRecord entity = this.service.findOne(id);
            if(entity != null){
                int status = entity.getStatus();
                String type = StringUtils.null2String(request.getParameter("type"));
                int changeStatus = status;
                if("cancel".equals(type)){//流程结束后取消会议室预约，释放会议室资源
                    if (status == 0) {
                        changeStatus = -1;
                    }else if(status == -1){
                    	failureMap.put("i18NCode", "oa.meeting.appointmentcancel");
                        return OperationResult.buildFailureResult("已取消预约",failureMap);
                    }else{
                    	failureMap.put("i18NCode", "oa.meeting.tip40");
                        return OperationResult.buildFailureResult("已发起会议，不可取消预约",failureMap);
                    }
                }else{
                    if("1".equals(nStatus)){//正常结束
                        changeStatus = 1;
                    }else if("0".equals(nStatus)){//驳回到发起人
                        changeStatus = 2;
                    }else if("3".equals(nStatus) || "2".equals(nStatus)){//发起人撤销或非正常结束
                        changeStatus = -1;
                    }else if("4".equals(nStatus)){//表单提交
                        changeStatus = 0;
                    }
                }
                List<String> ids = new ArrayList<>();
                ids.add(id);
                this.service.changeStatusById(changeStatus, ids);
                if(changeStatus == 1){//会议流程正常结束，会议为未召开状态，发送推送消息
                    this.service.editSaveByStatus(entity,"1","",TOKEN);
                    BoardroomSet room = null;
                    if(StringUtils.isNotEmpty(entity.getBoardroomId())) {
                    	room = this.boardroomSetService.findOne(entity.getBoardroomId());
                    }
                    WebUser user = WebUtils.getCurrentUser();
                    String corpId = user.getCorpId();
                    int nStauts = entity.getStatus();
                    String userIds = "", orgIds = "", jsonIds = "[";
                    Map<String, Object> ds = new HashMap<>();
                    ds.put("applyRecordId", id);
                    ds.put("meetingTitle", entity.getName());
                    ds.put("startTime", entity.getStartTime());
                    ds.put("boardroom", room==null?(StringUtils.isNotEmpty(entity.getAddress()) ? entity.getAddress():"无") : room.getAddress());
                    String noticeUserId = entity.getCreatedBy();
                    String userName = "";
                    if(StringUtils.isNotEmpty(noticeUserId)){
                        Map<String, Object> userInfo = this.userApiService.getUser(noticeUserId, corpId,  "", TOKEN);
                        if(userInfo != null){
                            userName = StringUtils.null2String(userInfo.get("userName"));
                        }
                    }
                    ds.put("userId", noticeUserId);
                    ds.put("userName", userName);
                    if(nStauts == 1){
                        ds.put("type", "2");
//                        Map<String, String> idsMap1 = new HashMap<>();
//                        idsMap1 = this.transformUserScopePlatform2Dd(entity.getEmceeUser(), "oa_meeting_apply_record", "emcee_user", corpId, TOKEN);
//                        userIds += idsMap1.get("ids");
//                        jsonIds += idsMap1.get("jsonIds");
//                        Map<String, String> idsMap2 = new HashMap<>();
//                        idsMap2 = this.transformUserScopePlatform2Dd(entity.getMemoUser(), "oa_meeting_apply_record", "memo_user", corpId, TOKEN);
//                        userIds += idsMap2.get("ids");
//                        jsonIds += idsMap2.get("jsonIds");
//                        Map<String, String> uoMap = new HashMap<>();
//                        uoMap = this.transformUOScopePlatform2Dd(entity.getAttendUser(), "oa_meeting_apply_record", "attend_user", corpId, TOKEN);
//                        userIds += uoMap.get("userIds");
//                        orgIds += uoMap.get("orgIds");
//                        jsonIds += uoMap.get("jsonIds");
                        List<String> userIdList = this.service.getApplyRecordUserList(entity, TOKEN);
            			if(CollectionUtils.isNotEmpty(userIdList)){
            				StringBuffer idsBuffer = new StringBuffer();
            				StringBuffer jsonIdsBuffer = new StringBuffer("[");
            				for(int i = 0; i < userIdList.size(); i++) {
            					if(i == userIdList.size() - 1) {
            						idsBuffer.append(userIdList.get(i));
            						jsonIdsBuffer.append("{\"10\":\"" + userIdList.get(i) + "\"}]");
            					}else {
            						idsBuffer.append(userIdList.get(i) + ",");
            						jsonIdsBuffer.append("{\"10\":\"" + userIdList.get(i) + "\"},");
            					}
            				}
            				jsonIdsBuffer.append("]");
            				userIds = idsBuffer.toString();
            				jsonIds = jsonIdsBuffer.toString();
            			}
                        
                    }
                    
                    if(!StringUtils.isEmpty(userIds)){
                    	boolean mobilePush = false;
    		            boolean emailPush = false;
    		            boolean smsPublish = false;
    					String mesgPush = entity.getMessagePush();
    					if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("mobile")) mobilePush = true;
    					if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("email")) emailPush = true;
    					if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("sms")) smsPublish = true;
                        ds.put("userIds", userIds);
                        ds.put("orgIds", "");
                        this.meetingSendMsgUtils.sendMail(ds, emailPush, corpId, TOKEN);
                        this.meetingSendMsgUtils.sendMsgToApp(ds, mobilePush, corpId, TOKEN, request);
    					this.meetingSendMsgUtils.sendSMS(ds, smsPublish, corpId, TOKEN);
                    }
                    if(StringUtils.isNotEmpty(jsonIds) && !"[]".equals(jsonIds)){
                        this.meetingSendMsgUtils.sendMessage(ds, jsonIds, corpId, TOKEN);
                    }
                }
                failureMap.put("i18NCode", "oa.meeting.savesuccess");
                return OperationResult.buildSuccessResult("保存成功",failureMap);
            }
        }
        failureMap.put("i18NCode", "oa.meeting.tip41");
        return OperationResult.buildFailureResult("该预约不存在",failureMap);
    }
    
    /**
     * 修改会议状态
     */
    @RequestMapping(value = "/endApplyRecord", method = RequestMethod.POST)
    public OperationResult endApplyRecord(Model model,HttpServletRequest request) {
    	Map failureMap = new HashMap();
    	String id = ValidateUtils.filter(request.getParameter("applyRecordId"));
    	ApplyRecord record = this.service.findOne(id);
    	if(record != null){
    		record.setStatus(5);
    		String current = DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm");
    		record.setEndTime(current);
    		return super.editSave(record);
    	}else {
    		failureMap.put("i18NCode", "oa.meeting.datadelsuccess");
    		return OperationResult.buildFailureResult("当前数据已删除",failureMap);
    	}
    }
    
    /**
     * 修改签到状态
     */
    @RequestMapping(value = "/updateSignInfo", method = RequestMethod.POST)
    public OperationResult updateSignInfo(HttpServletRequest request) {
    	Map failureMap = new HashMap();
    	String recordId = ValidateUtils.filter(request.getParameter("applyRecordId"));
    	String id = ValidateUtils.filter(request.getParameter("signedId"));
    	String signedUserId = ValidateUtils.filter(request.getParameter("signedUserId"));
    	String isSigned = ValidateUtils.filter(request.getParameter("isSigned"));
    	String signedTime = ValidateUtils.filter(request.getParameter("signedTime"));
    	SignedInfo signedInfo = this.signedInfoService.findOne(id);
    	if(signedInfo == null){
    		signedInfo = new SignedInfo();
    	}
    	ApplyRecord record = this.service.findOne(recordId);
		if(record != null){
			String signed = null;
			if("1".equals(isSigned)){//修改为已签到
				String signedType = record.getSignedType();
//				String currentDate = DateUtils.formatTimeNow();
				Date signedDate = String2Date(signedTime);
				if("0".equals(signedType)){//扫码签到
					signed = "s";
					signedInfo.setQrcodeTime(signedDate);
				}else{
					if("1".equals(signedType)){//定位签到
						signed = "d";
					}else if("2".equals(signedType)){//扫码+定位签到
						signed = "sd";
						signedInfo.setQrcodeTime(signedDate);
					}else if("3".equals(signedType)){//现场签到
						signed = "xc";
						signedInfo.setQrcodeTime(signedDate);
					}
					signedInfo.setPositionTime(signedDate);
					List<SignedAddress> list = this.signedAddressService.findByRecordId(recordId);
					if(list!=null && list.size()>0){
						SignedAddress address = list.get(0);
						signedInfo.setSignedAddress(address.getSignedAddress());
					}
				}
			}else {
				signedInfo.setSignedAddress(null);
			}
			signedInfo.setIsSigned(signed);
			signedInfo.setApplyRecordId(recordId);
			signedInfo.setSignedUserId(signedUserId);
			this.signedInfoService.save(signedInfo);
		}else{
			failureMap.put("i18NCode", "oa.meeting.savefalse");
			OperationResult.buildFailureResult("保存失败",failureMap);
		}
		failureMap.put("i18NCode", "oa.meeting.savesuccess");
    	return OperationResult.buildSuccessResult("保存成功",failureMap);
    }
    
    private Date String2Date(String date) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //加上时间
        //必须捕获异常
        try {
            return simpleDateFormat.parse(date);
        } catch(Exception px) {
            px.printStackTrace();
        }
        return new Date();
    }
    
    /**
     * 查询会议参会详细
     */
    @RequestMapping(value = "/userDetailList", method = RequestMethod.GET)
    public Page userDetailList(HttpServletRequest request) {
        Pageable localPageable = PropertyFilter.buildPageableFromHttpRequest(request);
        //会议id
        String applyrecordId = ValidateUtils.filter(request.getParameter("applyrecordId"));
        //参会情况
        String noticeType = ValidateUtils.filter(request.getParameter("noticeType"));
        //签到情况
        String signedType = ValidateUtils.filter(request.getParameter("signedType"));
        return this.service.getUserDetailList(localPageable,applyrecordId,noticeType,signedType,TOKEN);
    }
    
    /**
     * 会议视图查看页面
     * 
     * @param model
     * @return
     */
    @RequestMapping(value = "/meetingViewShow", method = RequestMethod.GET)
    public Map<String, Object> meetingViewShow(HttpServletRequest request) {
    	LOGGER.debug("-----meetingViewShow----");
        Map<String,Object> result = new HashMap<String,Object>();
        WebUser user = WebUtils.getCurrentUser();
        String corpId = "";
        String userId = "";
        if (user != null) {
            corpId = user.getCorpId();
            userId = user.getUserId();
        }
        String isSearch = ValidateUtils.filter(request.getParameter("isSearch"));
        String cateId = ValidateUtils.filter(request.getParameter("cateId"));
        //查询类别 0：天  1：周
        String isWeek = ValidateUtils.filter(request.getParameter("isWeek"));
        //查询天数
        String startDate = ValidateUtils.filter(request.getParameter("startDate"));
        String boardroomName = null, categoryId = null, count = null, meetingServe = null, address = null;
        List<Map> bsList = null;
        if("1".equals(isSearch)) {//查询       
        	boardroomName = request.getParameter("boardroomName");
        	categoryId = request.getParameter("categoryId");
        	count = request.getParameter("count");
        	meetingServe = request.getParameter("meetingServe");
        	address = request.getParameter("address");
        }else {
        	categoryId = cateId;
        }
        bsList = this.boardroomSetService.getBoardroomInfoList(boardroomName, categoryId, count, meetingServe, address, corpId);
        
    	List<String> bsIdsList = new ArrayList<String>();
    	
        if(CollectionUtils.isNotEmpty(bsList)) {
        	List<String> aScopeList = null;
        	String scopeuseUser = "";
         	for(Map m : bsList) {
         		
         		bsIdsList.add(StringUtils.null2String(m.get("id")));
         	}
        }
        Map<String, String> params = new HashMap<>();
    	params.put("userId", user.getUserId());
    	params.put("corpId", corpId);
    	params.put("token", user.getJwtToken());
    	LOGGER.debug("--startDate:"+startDate);
        if(StringUtils.isNotEmpty(startDate)){
        	startDate = DateUtils.formatDate(DateUtils.parseDate(startDate));
        }else{
        	startDate = DateUtils.formatDateNow();
        }
        List<Map<String,Object>> brList = new ArrayList<>();
        List<Map<String,Object>> arList = new ArrayList<>();
        if("0".equals(isWeek)){
        	brList = this.service.getBoardRoomInfos(bsList, startDate);
        	arList = this.service.getApplyRecordInfos(bsList,bsIdsList,startDate,startDate,params);
        }else{
        	String endDate = ValidateUtils.filter(request.getParameter("endDate"));
        	if(StringUtils.isNotEmpty(endDate)){
            	endDate = DateUtils.formatDate(DateUtils.parseDate(endDate));
            }else{
            	endDate = DateUtils.formatDateNow();
            }
        	brList = this.service.getBoardRoomInfos(bsList, startDate);
//        	brList = this.service.getBoardRoomInfos(bsList, startDate, endDate);
        	arList = this.service.getApplyRecordInfos(bsList,bsIdsList,startDate,endDate,params);
        }
        result.put("boardRoomData", brList);
        result.put("applyRecordList", arList);
        
        return result;
    }
    
    private boolean compareUserId(List<String> unitUserList,String userId) {
    	
    	if(CollectionUtils.isNotEmpty(unitUserList)){
           for (String uid:unitUserList) {
        	  if (userId.equals(uid)) {
        		return true;
        	  }
          }
    	}
    	return false;
    	
    }
    /**
     * 会议日历数据
     * 
     * @param model
     * @return
     */
    @RequestMapping(value = "/meetingCalendarShow", method = RequestMethod.GET)
    public Map<String, Object> meetingCalendarShow(HttpServletRequest request) {
    	WebUser wuser=WebUtils.getCurrentUser();
    	LOGGER.debug("-----meetingCalendarShow----");
    	List<Map> userL=this.service.findByListNativeQuery("select user_status as userStatus,is_delete as isDelete from sys_user where id='"+wuser.getUserId()+"'", "");
		if(userL!=null && userL.size()>0) {
			Map userStatus=userL.get(0);
			if("offDuty".equals(userStatus.get("userStatus"))||"1".equals(userStatus.get("isDelete")+"")) {
				return new HashMap<String, Object>(){
					private static final long serialVersionUID = 4536909507398695835L;
					{
						this.put("applyRecordList", new ArrayList<>(0));
					}};
			}
		}
    	String type = "0";
    	String isend = request.getParameter("isend");
    	String ijoin = request.getParameter("ijoin");
    	if("1".equals(isend)&&"1".equals(ijoin)) {
    		type = "0";
    	}else if("1".equals(isend)&&"0".equals(ijoin)) {
    		type = "1";
    	}else if("0".equals(isend)&&"1".equals(ijoin)) {
    		type = "2";
    	}else if("0".equals(isend)&&"0".equals(ijoin)) {
    		type = "-1";
    	}
    	
        Map<String,Object> result = new HashMap<String,Object>();
        WebUser user = WebUtils.getCurrentUser();
        String corpId = "";
        if (user != null) {
            corpId = user.getCorpId();
        }
    	Map<String, String> params = new HashMap<>();
    	params.put("userId", user.getUserId());
    	params.put("corpId", corpId);
    	params.put("token", user.getJwtToken());
    	//查询天数
        String startDate = ValidateUtils.filter(request.getParameter("startDate"));
        if(StringUtils.isNotEmpty(startDate)){
        	startDate = DateUtils.formatDate(DateUtils.parseDate(startDate));
        }else{
        	startDate = DateUtils.formatDateNow();
        }
    	String endDate = ValidateUtils.filter(request.getParameter("endDate"));
    	if(StringUtils.isNotEmpty(endDate)){
        	endDate = DateUtils.formatDate(DateUtils.parseDate(endDate));
        }else{
        	endDate = DateUtils.formatDateNow();
        }
    	List<Map<String,Object>> arList = this.service.getCalendarApplyRecordInfo(startDate,endDate,params,type);
        result.put("applyRecordList", arList);
        
        return result;
    }
    
    /**
     * 新建会议查看会议视图
     * 
     * @param model
     * @return
     */
    @RequestMapping(value = "/meetingBoardroomView", method = RequestMethod.GET)
    public List<Map<String,Object>> meetingBoardroomView(HttpServletRequest request) {
        WebUser user = WebUtils.getCurrentUser();
        String corpId = "";
        if (user != null) {
            corpId = user.getCorpId();
        }
        //查询天数
        String currentDate = ValidateUtils.filter(request.getParameter("searchDate"));
        if(StringUtils.isEmpty(currentDate)){
        	currentDate = DateUtils.formatDateNow();
        }
        List<BoardroomSet> bsList = this.boardroomSetService.getBoardroomSetList(corpId,"");
        List<Map<String,Object>> result = this.service.getApplyRecordView(bsList, currentDate);
        return result;
    }
    
	private Map<String, String> transformUserScopePlatform2Dd(String fieldDataValue, String table, String fieldData, String corpId, String token){
        String ids = "", jsonIds = "";
        Map<String, String> result = new HashMap<>();
        String scopeTypeStr = this.popUserScopeUtilService.getScopeTypeValue("oa_meeting_apply_record_scope", table, fieldData, StringUtils.null2String(fieldDataValue));
        String[] scopeTypeArray = scopeTypeStr.split(",");
        if(scopeTypeArray != null && scopeTypeArray.length>0) {
        	List<String> l = new ArrayList<>();
            for (int i = 0; i < scopeTypeArray.length; i++) {
                String[] info = scopeTypeArray[i].split("SCOPE");
                if (info.length > 1){
                	String id  = info[1];
                	String type  = info[0];
                	List<String> u = new ArrayList<>();
                	if("user".equals(type)){
                        jsonIds +="{\"10\":\""+id+"\"},";
                        l.add(id);
//                		u = this.userApiService.getUserIdBySysOrThird(id, "1", "DD", corpId, token);
                	}
//                    if(u!=null && u.size()>0){
//                    	l.addAll(u);
//                    }
                }
            }
            if(l!=null && l.size()>0){
            	for(int i=0; i<l.size(); i++){
            		String thirdId = l.get(i);
            		if(StringUtils.isNotEmpty(thirdId)){
            			ids += thirdId + ",";
            		}
            	}
            }
        }
        result.put("jsonIds", jsonIds);
        result.put("ids", ids);
        return result;
    }
	
	private Map<String, String> transformUOScopePlatform2Dd(String fieldDataValue, String table, String fieldData, String corpId, String token){
		Map<String, String> map = new HashMap<>();
		String ids = "", orgIds = "", jsonIds = "";
        String scopeTypeStr = this.popUserScopeUtilService.getScopeTypeValue("oa_meeting_apply_record_scope", table, fieldData, StringUtils.null2String(fieldDataValue));
        String[] scopeTypeArray = scopeTypeStr.split(",");
        if(scopeTypeArray != null && scopeTypeArray.length>0) {
        	List<String> l = new ArrayList<>();
        	List<String> o = new ArrayList<>();
            for (int i = 0; i < scopeTypeArray.length; i++) {
                String[] info = scopeTypeArray[i].split("SCOPE");
                if (info.length > 1){
                	String id  = info[1];
                	String type  = info[0];
                	if("user".equals(type)){
                        jsonIds +="{\"10\":\""+id+"\"},";
                        l.add(id);
//                		List<String> u = this.userApiService.getUserIdBySysOrThird(id, "1", "DD", corpId, token);
//                		if(u!=null && u.size()>0){
//                        	l.addAll(u);
//                        }
                	}else if("org".equals(type)){
                        jsonIds +="{\"20\":\""+id+"\"},";
                        o.add(id);
//                		List<String> u = this.orgApiService.getOrgIdOrThirdUid(id, "1", "DD", corpId, token);
//                		if(u!=null && u.size()>0){
//                            for(int j=0; j<u.size(); j++){
//                                if("1".equals(u.get(j))){
//                                    Map<String, Object> topOrgInfo = this.orgApiService.getPopuOrgChildInfo(id,"user", "","", "", corpId, token);
//                                    List<Map<String, Object>> userList = (List<Map<String, Object>>)topOrgInfo.get("userList");
//                                    List<Map<String, Object>> orgList = (List<Map<String, Object>>)topOrgInfo.get("orgList");
//                                    if(userList!=null && userList.size()>0){
//                                        for(int k=0; k<userList.size(); k++){
//                                            Map<String, Object> map1 = userList.get(k);
//                                            String ddUId = StringUtils.null2String(map1.get("ddUId"));
//                                            if(StringUtils.isNotEmpty(ddUId)){
//                                                l.add(ddUId);
//                                            }
//                                        }
//                                    }
//                                    if(orgList!=null && orgList.size()>0){
//                                        for(int k=0; k<orgList.size(); k++){
//                                            Map<String, Object> map1 = orgList.get(k);
//                                            String ddUId = StringUtils.null2String(map1.get("ddUId"));
//                                            if(StringUtils.isNotEmpty(ddUId)){
//                                                o.add(ddUId);
//                                            }
//                                        }
//                                    }
//                                }else{
//                                    o.add(u.get(j));
//                                }
//                            }
//                        }
                	}
                }
            }
            if(l!=null && l.size()>0){
            	for(int i=0; i<l.size(); i++){
            		String thirdId = l.get(i);
            		if(StringUtils.isNotEmpty(thirdId)){
            			ids += thirdId + ",";
            		}
            	}
            }
            if(o!=null && o.size()>0){
            	for(int i=0; i<o.size(); i++){
            		String thirdId = o.get(i);
            		if(StringUtils.isNotEmpty(thirdId)){
            			orgIds += thirdId + ",";
            		}
            	}
            }
        }
        map.put("jsonIds", jsonIds);
        map.put("userIds", ids);map.put("orgIds", orgIds);
        return map;
    }
	
	/**
	 * 生成二维码
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getQrcodeAttachment", method = RequestMethod.GET, produces = {"application/json; charset=UTF-8" })
	public Map<String, Object> getQrcodeAttachment(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			WebUser user = WebUtils.getCurrentUser();
			String id = request.getParameter("id");
			String corpId = user.getCorpId();
			
			GlobalConstant globalConstant = new GlobalConstant();// 读取配置文件class
	    	String qrcodeUrl = globalConstant.getConfig("app.flexoffice.qrcode.url");
	    	
//			String url = GlobalConstant.getFlexOfficePageUrl(request);
//			if(StringUtils.isEmpty(url)) url = GlobalConstant.getFlexOfficeQrcodeUrl(request);
			ApplyRecord record = this.service.findOne(id);
			String attachId = record.getQrcodeAttach();
//            Urlconvert urlconvert = new Urlconvert();
//            urlconvert.setDingUrl(this.getMessageUrl("0", id, corpId, TOKEN));
//            urlconvert.setWxUrl(this.getMessageUrl("1", id, corpId, TOKEN));
//            urlconvert.setMhUrl(this.getMessageUrl("2", id, corpId, TOKEN));
//            urlconvert = this.urlconvertService.save(urlconvert);
//            String qrUrl = "/mobile/modules/meeting/dist/index.html?dd_nav_bgcolor=FF5E97F6#/meeting/qrCodeRedirect/"+urlconvert.getId();
			String qrUrl = "/mobile/modules/meeting/dist/index.html?context="+qrcodeUrl+"&dd_nav_bgcolor=FF5E97F6#/meeting/qrcodeSign/" + id;
			attachId = this.createQrCode(request, qrUrl, TOKEN);
            record.setQrcodeAttach(attachId);
            this.service.save(record);
			map.put("attachments", attachId);
			if(StringUtils.isNotEmpty(attachId)){
        		List<Map<String, String>> images = this.attachmentUtilsService.getAttachmentByIds(attachId, corpId, TOKEN);
        		if(images!=null && images.size()>0){
        			Map<String, String> image = images.get(0);
//        			String severUrl = GlobalConstant.getFlexServerPath(request);
        			String severUrl = GlobalConstant.getAppWebUrl("flexbase");
        			map.put("image", severUrl + image.get("imageUrl"));
        		}
        	}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}
	
	/**
	 * 获取各个平台签到路径
	 * @param type 0:钉钉 1:企业微信 2:移动平台
	 * @param id
	 * @param webUrl
	 * @param corpId
	 * @param token
	 * @return
	 */
	private String getMessageUrl(String type, String id, String corpId, String token) {
		String messageUrl = "";
		String appId = "";
		String corpReally = "";
		if("2".equals(type)) {
			messageUrl = "/mobile/modules/meeting/dist/index.html?dd_nav_bgcolor=FF5E97F6#/meeting/qrcodeSign/" + id;
		}else {
			Map<String,Object> mpMap = mobileParamdataService.getParamDataMap(corpId, "meeting", type, token);
	    	if(MapUtils.isNotEmpty(mpMap)) {
	    		String code = String.valueOf(mpMap.get("code"));
	    		if(code.equals("0")) {//获取成功
	    			corpReally = String.valueOf(mpMap.get("corpId"));
	    			appId = String.valueOf(mpMap.get("agentId"));
	    		}
	    	}
			messageUrl = "/mobile/modules/meeting/dist/index.html"
	                + "?appid=" + appId
	                + "&corpid=" + corpReally
	                + "&dd_nav_bgcolor=FF5E97F6#/meeting/qrcodeSign"
	                + "/" + id;
		}
		return messageUrl;
	}
	
	/**
     * 生成二维码图片
     *
     * @param content
     */
    public String createQrCode(HttpServletRequest request, String content, String token) {
    	String attId = "";
    	try {
    		//计算二维码图片的高宽比
            // API文档规定计算图片宽高的方式 ，v是本次测试的版本号
            int v = 9;
            int width = 67 + 12 * (v - 1);
            int height = 67 + 12 * (v - 1);
        	Qrcode qrcode = new Qrcode();  
            qrcode.setQrcodeErrorCorrect('M');//纠错等级（分为L、M、H三个等级）  
            qrcode.setQrcodeEncodeMode('B');//N代表数字，A代表a-Z，B代表其它字符  
            qrcode.setQrcodeVersion(v);//版本    
            BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  
            //绘图  
            Graphics2D gs = bufferedImage.createGraphics();  
            gs.setBackground(Color.WHITE);  
            gs.setColor(Color.BLACK);  
            gs.clearRect(0, 0, width, height);//清除下画板内容  
              
            //设置下偏移量,如果不加偏移量，有时会导致出错。  
            int pixoff = 2; 
            //String qrData="www.baidu.com";
              
            byte[] d = content.getBytes("utf-8");  
            if(d.length > 0){  
                boolean[][] s = qrcode.calQrcode(d);
                for(int i=0;i<s.length;i++){  
                    for(int j=0;j<s.length;j++){  
                        if(s[j][i]){  
                            gs.fillRect(j*3+pixoff, i*3+pixoff, 3, 3);  
                        }  
                    }  
                }  
            }  
            gs.dispose();  
            bufferedImage.flush();  

            // 生成二维码QRCode图片
            String pathTime=DateUtils.formatDate(new Date(), "yyyyMMddHHmmssSSS");
		    String path = org.ezplatform.util.http.WebUtils.getWebRealPath(request)+"attachment\\meetingUpload\\"+pathTime+"\\" ;
			File file = new File(path);
			if(!file.exists()){//判断文件目录是否存在    
				file.mkdirs();  
            }  
			String filePath = path + "qrcode" + pathTime + ".png";
			file = new File(filePath);
            // 生成的图片在D盘下，名为 qrCode.png
			ImageIO.write(bufferedImage, "png", file);
			
            List<Map<String,Object>> list =(List<Map<String, Object>>) this.attachmentUtilsService.upload("meeting",file,token);
    		if(null!=list && list.size()>0){
    			list.get(0).get("id");
    			if(StringUtils.isNotBlank(attId)){
    				attId+="|"+list.get(0).get("id");
    			}else{
    				attId=(String) list.get(0).get("id");
    			}
    		}
    		file.delete();
    		File f = new File(path);
    		if(f.exists()){
    			f.delete();
    		}
        } catch (Exception e) {
            e.printStackTrace();
        }
    	return attId;
    }
    
    /**
	 * 查询已申请会议室列表数据(分页)
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/applyBoardroomList", method = RequestMethod.GET, produces = {"application/json; charset=UTF-8" })
    public Page getApplyBoardroomList(HttpServletRequest request) {
		WebUser user = WebUtils.getCurrentUser();
		String corpId = user.getCorpId();
		String userId = user.getUserId();
		Pageable pageable = PropertyFilter.buildPageableFromHttpRequest(request);
		String boardroomName = ValidateUtils.filter(request.getParameter("boardroomName"));
		String startTime = ValidateUtils.filter(request.getParameter("startTime"));
		String endTime = ValidateUtils.filter(request.getParameter("endTime"));
		String categoryId = ValidateUtils.filter(request.getParameter("categoryId"));
		String boardroomStatus = ValidateUtils.filter(request.getParameter("boardroomStatus"));
		return service.findApplyBoardroomListByPage(pageable, corpId, userId, boardroomName, startTime, endTime, categoryId, boardroomStatus);
    }
	
	/**
     * 删除（批量）已预定但未召开会议室数据
     * @param ids
     * @return
     */
    @RequestMapping(value = "/deleteApplyBoardroom", method = RequestMethod.POST)
    public OperationResult deleteApplyBoardroom(@RequestParam("ids") String... ids) {
    	Map failureMap = new HashMap();
    	List<ApplyRecord> list = service.findAll(ids);
    	if(CollectionUtils.isNotEmpty(list)) {
    		for(ApplyRecord a : list) {
    			if(a.getIsSync() == 1) return OperationResult.buildFailureResult("已使用会议室无法删除");
    		}
    	}
    	OperationResult result = super.delete(ids);
    	if("0".equals(result.getCode())) {
    		failureMap.put("i18NCode", "oa.meeting.tip25");
    		return OperationResult.buildSuccessResult("取消成功",failureMap);
    	}else {
    		failureMap.put("i18NCode", "oa.meeting.tip26");
    		return OperationResult.buildFailureResult("取消失败",failureMap);
    	}
    }
    
    /**
	 * 查询可以使用的会议室列表数据(分页)
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/canUseBoardroomList", method = RequestMethod.GET, produces = {"application/json; charset=UTF-8" })
    public Page findCanUseBoardroomListByPage(HttpServletRequest request) {
		WebUser user = WebUtils.getCurrentUser();
		String corpId = user.getCorpId();
		String userId = user.getUserId();
		Pageable pageable = PropertyFilter.buildPageableFromHttpRequest(request);
		String boardroomName = ValidateUtils.filter(request.getParameter("boardroomName"));
		String startTime = ValidateUtils.filter(request.getParameter("startTime"));
		String endTime = ValidateUtils.filter(request.getParameter("endTime"));
		String categoryId = ValidateUtils.filter(request.getParameter("categoryId"));
		String isCycle = ValidateUtils.filter(request.getParameter("isCycle"));//查询已预定周期会议
		return service.findCanUseBoardroomListByPage(pageable, corpId, userId, boardroomName, startTime, endTime, categoryId, isCycle);
    }
	
	@RequestMapping(value = "/getMapKey", method = RequestMethod.GET, produces = {"application/json; charset=UTF-8" })
	public OperationResult getMapKey() {
		try {
			String key = GlobalConstant.getConfig("app.flexoffice.amap.key");
			return OperationResult.buildSuccessResult("获取地图key成功", key);
		} catch (Exception e) {
			e.printStackTrace();
			return OperationResult.buildFailureResult("获取地图key失败");
		}
	}
	
	@RequestMapping(value = "/getCreatedbyNameAndApplyInfo", method = RequestMethod.GET)
	public OperationResult getCreatedbyNameAndApplyInfo(@ModelAttribute("entity") ApplyRecord entity, Model model,HttpServletRequest request) {
		
		Map<String,Object>reMap=new HashMap<>();
		String createdName=cmpPopUserOrgName.getUserNameById(entity.getCreatedBy());
		reMap.put("createdName", createdName);
		reMap.put("name", entity.getName());
		return OperationResult.buildSuccessResult("获取成功", reMap);
	}
	
	   /**
     * 获取模板列表
     * @param request
     * @return
     */
    @RequestMapping(value = "/getTempletFileList", method = RequestMethod.GET)
    @ResponseBody
    public OperationResult getTempletFileList(HttpServletRequest request) {

        Map<String, Object> resultMap = new HashMap<String, Object>();

        WebUser user = WebUtils.getCurrentUser();
        String corpId = user.getCorpId();

        String recordId = request.getParameter("recordId") == null ? "" : request.getParameter("recordId");
        String moduleCode = request.getParameter("moduleCode") == null ? "" : request.getParameter("moduleCode");
        String type = StringUtils.null2String(request.getParameter("type"));//模板类型 goldgrid 金格编辑 wps wps编辑 yozo 永中office
        String fileNoTemplateId = StringUtils.null2String(request.getParameter("fileNoTemplateId"));//文号对应模板id
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("userId", user.getUserId());
        paramMap.put("corpId", corpId);
        paramMap.put("moduleCode", moduleCode);
        paramMap.put("recordId", recordId);
        paramMap.put("type", type);
        paramMap.put("fileNoTemplateId", fileNoTemplateId);

        String optionHtml = "<option value=''>--请选择--</option>";
        String TemplateFileStr = "";
        try {
            // 查询当前用户具有查看流程的权限以及是否是流程管理员
            TemplateFileStr = restClient.get("/cmp/goldgrid/templatefile/getTemplateFileListMap", user.getJwtToken(),
                    paramMap);
            Map<String, Object> map = JsonUtils.readValue(TemplateFileStr);
            if (StringUtils.null2String(map.get("success")).equals("true")) {
                Map<String, Object> contentMap = (Map<String, Object>) map.get("content");
                List<Map<String, Object>> templateFileDataList = (List<Map<String, Object>>) contentMap
                        .get("templateFileDataList");
                
                if (templateFileDataList != null && templateFileDataList.size() > 0) {
                	int templateSize=templateFileDataList.size();
                	if(templateSize==1) {
                		resultMap.put("oneTemplate", templateFileDataList.get(0));
                	}
                    for (Map<String, Object> map_ : templateFileDataList) {
                        optionHtml += "<option value='" + map_.get("recordId") + "'>" + map_.get("fileName")
                                + "</option>";
                    }
                }
                resultMap.put("officeType", contentMap.get("type") + "");
            } else {
                resultMap.put("officeType", "goldgrid");
            }
        } catch (Exception e) {
            resultMap.put("officeType", "goldgrid");
            e.printStackTrace();
        }
        resultMap.put("optionHtml", optionHtml);
        return OperationResult.buildSuccessResult(resultMap);
    }
    
	public static void main(String[] args) {

		//System.out.println(UuidUtils.UUID());
		System.out.println( "".indexOf("|2|"));
	}
	
}
